Skip to main content

ftui_layout/
lib.rs

1#![forbid(unsafe_code)]
2
3//! Layout primitives and solvers.
4//!
5//! This crate provides layout components for terminal UIs:
6//!
7//! - [`Flex`] - 1D constraint-based layout (rows or columns)
8//! - [`Grid`] - 2D constraint-based layout with cell spanning
9//! - [`Constraint`] - Size constraints (Fixed, Percentage, Min, Max, Ratio, FitContent)
10//! - [`debug`] - Layout constraint debugging and introspection
11//! - [`cache`] - Layout result caching for memoization
12//!
13//! # Role in FrankenTUI
14//! `ftui-layout` is the geometry solver for widgets and screens. It converts
15//! constraints into concrete rectangles, with support for intrinsic sizing and
16//! caching to keep layout deterministic and fast.
17//!
18//! # How it fits in the system
19//! The runtime and widgets call into this crate to split a `Rect` into nested
20//! regions. Those regions are then passed to widgets or custom renderers, which
21//! ultimately draw into `ftui-render` frames.
22//!
23//! # Intrinsic Sizing
24//!
25//! The layout system supports content-aware sizing via [`LayoutSizeHint`] and
26//! [`Flex::split_with_measurer`]:
27//!
28//! ```ignore
29//! use ftui_layout::{Flex, Constraint, LayoutSizeHint};
30//!
31//! let flex = Flex::horizontal()
32//!     .constraints([Constraint::FitContent, Constraint::Fill]);
33//!
34//! let rects = flex.split_with_measurer(area, |idx, available| {
35//!     match idx {
36//!         0 => LayoutSizeHint { min: 5, preferred: 20, max: None },
37//!         _ => LayoutSizeHint::ZERO,
38//!     }
39//! });
40//! ```
41
42pub mod cache;
43pub mod debug;
44pub mod dep_graph;
45pub mod direction;
46pub mod egraph;
47pub mod grid;
48pub mod incremental;
49pub mod pane;
50pub mod pane_command;
51pub mod pane_execution;
52pub mod pane_memory;
53pub mod pane_monitors;
54pub mod pane_persistent;
55pub mod pane_retention;
56#[cfg(test)]
57mod repro_max_constraint;
58#[cfg(test)]
59mod repro_space_around;
60pub mod responsive;
61pub mod responsive_layout;
62pub mod veb_tree;
63pub mod visibility;
64pub mod wide_prefix;
65pub mod workspace;
66
67#[cfg(feature = "experimental")]
68pub use cache::S3FifoLayoutCache;
69pub use cache::{CoherenceCache, CoherenceId, LayoutCache, LayoutCacheKey, LayoutCacheStats};
70pub use direction::{FlowDirection, LogicalAlignment, LogicalSides, mirror_rects_horizontal};
71pub use ftui_core::geometry::{Rect, Sides, Size};
72pub use grid::{Grid, GridArea, GridLayout};
73pub use pane::{
74    PANE_AFFORDANCE_EMPHASIS_FULL_BPS, PANE_DEFAULT_MARGIN_CELLS, PANE_DEFAULT_PADDING_CELLS,
75    PANE_DRAG_RESIZE_DEFAULT_HYSTERESIS, PANE_DRAG_RESIZE_DEFAULT_THRESHOLD,
76    PANE_EDGE_GRIP_INSET_CELLS, PANE_MAGNETIC_FIELD_CELLS,
77    PANE_SEMANTIC_INPUT_EVENT_SCHEMA_VERSION, PANE_SEMANTIC_INPUT_TRACE_SCHEMA_VERSION,
78    PANE_SNAP_DEFAULT_HYSTERESIS_BPS, PANE_SNAP_DEFAULT_STEP_BPS, PANE_TREE_SCHEMA_VERSION,
79    PaneAffordanceMotion, PaneCancelReason, PaneConstraints, PaneCoordinateNormalizationError,
80    PaneCoordinateNormalizer, PaneCoordinateRoundingPolicy, PaneDockPreview, PaneDockZone,
81    PaneDragBehaviorTuning, PaneDragResizeEffect, PaneDragResizeMachine,
82    PaneDragResizeMachineError, PaneDragResizeNoopReason, PaneDragResizeState,
83    PaneDragResizeTransition, PaneEdgeResizePlan, PaneEdgeResizePlanError, PaneGroupTransformPlan,
84    PaneId, PaneIdAllocator, PaneInertialThrow, PaneInputCoordinate, PaneInteractionPolicyError,
85    PaneInteractionTimeline, PaneInteractionTimelineCheckpointDecision,
86    PaneInteractionTimelineEntry, PaneInteractionTimelineError,
87    PaneInteractionTimelineReplayDiagnostics, PaneInteractionTimelineRetentionDiagnostics,
88    PaneInvariantCode, PaneInvariantIssue, PaneInvariantReport, PaneInvariantSeverity, PaneLayout,
89    PaneLayoutIntelligenceMode, PaneLeaf, PaneModelError, PaneModifierSnapshot, PaneMotionVector,
90    PaneNodeKind, PaneNodeRecord, PaneNormalizedCoordinate, PaneOperation, PaneOperationError,
91    PaneOperationFailure, PaneOperationFamily, PaneOperationJournalEntry,
92    PaneOperationJournalResult, PaneOperationKind, PaneOperationOutcome, PanePlacement,
93    PanePointerButton, PanePointerPosition, PanePrecisionMode, PanePrecisionPolicy,
94    PanePressureSnapProfile, PaneReflowMovePlan, PaneReflowPlanError, PaneRepairAction,
95    PaneRepairError, PaneRepairFailure, PaneRepairOutcome, PaneResizeDirection, PaneResizeGrip,
96    PaneResizeTarget, PaneScaleFactor, PaneSelectionState, PaneSemanticInputEvent,
97    PaneSemanticInputEventError, PaneSemanticInputEventKind, PaneSemanticInputTrace,
98    PaneSemanticInputTraceError, PaneSemanticInputTraceMetadata,
99    PaneSemanticReplayConformanceArtifact, PaneSemanticReplayDiffArtifact,
100    PaneSemanticReplayDiffKind, PaneSemanticReplayError, PaneSemanticReplayFixture,
101    PaneSemanticReplayOutcome, PaneSnapDecision, PaneSnapReason, PaneSnapTuning, PaneSplit,
102    PaneSplitRatio, PaneTransaction, PaneTransactionOutcome, PaneTree, PaneTreeSnapshot, SplitAxis,
103};
104pub use pane_command::{
105    PaneAccessibilityPreferences, PaneAnnouncement, PaneAnnouncementCategory, PaneAnnouncer,
106    PaneCardinalDirection, PaneCommand, PaneCommandAcceleration, PaneCommandEffect,
107    PaneCommandNoopReason, PaneCommandResolution, PaneFocusContext, PaneFocusOrdinal,
108    PaneKeymapOwner, PaneKeymapPrecedence, announce_command, focus_cyclic, focus_directional,
109    focus_edge, focus_order, resolve as resolve_pane_command,
110};
111pub use pane_execution::{
112    PaneExecutionDecision, PaneExecutionEngine, PaneExecutionError, PaneExecutionPolicy,
113    PaneExecutionSample, PaneExecutionStatus, PaneHistory, PaneStrategyReason, PaneWorkloadProfile,
114};
115pub use pane_memory::{
116    PANE_MEMORY_TELEMETRY_SCHEMA_VERSION, PaneMemoryComparison, PaneMemoryDriver,
117    PaneMemoryStrategy, PaneMemoryStrategyFootprint, pane_memory_comparison,
118};
119pub use pane_monitors::{
120    PaneAssumption, PaneMonitorReport, PaneMonitorStatus, PaneMonitorThresholds,
121    PaneMonitorVerdict, monitor_fallback_frequency, monitor_latency_envelope, monitor_replay_depth,
122    monitor_retention_pressure, monitor_selector_churn,
123};
124pub use pane_persistent::{
125    PaneVersionRetention, PaneVersionStore, PaneVersioningReport, PersistentApplyError,
126    PersistentApplyStrategy, PersistentNode, VersionedPaneTree,
127};
128pub use pane_retention::{
129    PaneRetentionBudget, PaneRetentionDecision, PaneRetentionOutcome, PaneRetentionPolicy,
130    apply_to_timeline as apply_retention_to_timeline,
131    apply_to_version_store as apply_retention_to_version_store,
132};
133pub use responsive::Responsive;
134pub use responsive_layout::{ResponsiveLayout, ResponsiveSplit};
135pub use smallvec;
136use smallvec::SmallVec;
137use std::cmp::min;
138pub use visibility::Visibility;
139pub use wide_prefix::{WidePrefixError, WidePrefixSums};
140pub use workspace::{
141    MigrationResult, WORKSPACE_SCHEMA_VERSION, WorkspaceMetadata, WorkspaceMigrationError,
142    WorkspaceSnapshot, WorkspaceSnapshotJsonError, WorkspaceValidationError,
143    canonicalize_workspace_snapshot, decode_workspace_snapshot_json, migrate_workspace,
144    needs_migration, to_canonical_workspace_snapshot_json,
145};
146
147/// Inline capacity for layout result vectors.
148///
149/// Most layouts use ≤8 constraints, so inlining avoids heap allocation in the
150/// common case. The `SmallVec` spills to the heap transparently when needed.
151const LAYOUT_INLINE_CAP: usize = 8;
152
153/// Stack-inlined vector of rectangles returned by layout split operations.
154pub type Rects = SmallVec<[Rect; LAYOUT_INLINE_CAP]>;
155
156/// Stack-inlined vector of sizes returned by the constraint solver.
157type Sizes = SmallVec<[u16; LAYOUT_INLINE_CAP]>;
158
159/// Stack-inlined vector of flex constraints.
160type Constraints = SmallVec<[Constraint; LAYOUT_INLINE_CAP]>;
161
162/// A constraint on the size of a layout area.
163#[derive(Debug, Clone, Copy, PartialEq)]
164pub enum Constraint {
165    /// An exact size in cells.
166    Fixed(u16),
167    /// A percentage of the total available size (0.0 to 100.0).
168    Percentage(f32),
169    /// A minimum size in cells.
170    Min(u16),
171    /// A maximum size in cells.
172    Max(u16),
173    /// A ratio of the total available space (numerator, denominator).
174    Ratio(u32, u32),
175    /// Fill remaining space (like Min(0) but semantically clearer).
176    Fill,
177    /// Size to fit content using widget's preferred size from [`LayoutSizeHint`].
178    ///
179    /// When used with [`Flex::split_with_measurer`], the measurer callback provides
180    /// the size hints. Defaults to zero size if no measurer is provided.
181    FitContent,
182    /// Fit content but clamp to explicit bounds.
183    ///
184    /// The allocated size will be between `min` and `max`, using the widget's
185    /// preferred size when within range.
186    FitContentBounded {
187        /// Minimum allocation regardless of content size.
188        min: u16,
189        /// Maximum allocation regardless of content size.
190        max: u16,
191    },
192    /// Use widget's minimum size (shrink-to-fit).
193    ///
194    /// Allocates only the minimum space the widget requires.
195    FitMin,
196}
197
198/// Size hint returned by measurer callbacks for intrinsic sizing.
199///
200/// This is a 1D projection of a widget's size constraints along the layout axis.
201/// Use with [`Flex::split_with_measurer`] for content-aware layouts.
202///
203/// # Example
204///
205/// ```
206/// use ftui_layout::LayoutSizeHint;
207///
208/// // A label that needs 5-20 cells, ideally 15
209/// let hint = LayoutSizeHint {
210///     min: 5,
211///     preferred: 15,
212///     max: Some(20),
213/// };
214///
215/// // Clamp allocation to hint bounds
216/// assert_eq!(hint.clamp(10), 10); // Within range
217/// assert_eq!(hint.clamp(3), 5);   // Below min
218/// assert_eq!(hint.clamp(30), 20); // Above max
219/// ```
220#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
221pub struct LayoutSizeHint {
222    /// Minimum size (widget clips below this).
223    pub min: u16,
224    /// Preferred size (ideal for content).
225    pub preferred: u16,
226    /// Maximum useful size (None = unbounded).
227    pub max: Option<u16>,
228}
229
230impl LayoutSizeHint {
231    /// Zero hint (no minimum, no preferred, unbounded).
232    pub const ZERO: Self = Self {
233        min: 0,
234        preferred: 0,
235        max: None,
236    };
237
238    /// Create an exact size hint (min = preferred = max).
239    #[inline]
240    pub const fn exact(size: u16) -> Self {
241        Self {
242            min: size,
243            preferred: size,
244            max: Some(size),
245        }
246    }
247
248    /// Create a hint with minimum and preferred size, unbounded max.
249    #[inline]
250    pub const fn at_least(min: u16, preferred: u16) -> Self {
251        Self {
252            min,
253            preferred,
254            max: None,
255        }
256    }
257
258    /// Clamp a value to this hint's bounds.
259    #[inline]
260    pub fn clamp(&self, value: u16) -> u16 {
261        let max = self.max.unwrap_or(u16::MAX);
262        value.min(max).max(self.min)
263    }
264}
265
266/// The direction to layout items.
267#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
268pub enum Direction {
269    /// Top to bottom.
270    #[default]
271    Vertical,
272    /// Left to right.
273    Horizontal,
274}
275
276/// Alignment of items within the layout.
277#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
278pub enum Alignment {
279    /// Align items to the start (left/top).
280    #[default]
281    Start,
282    /// Center items within available space.
283    Center,
284    /// Align items to the end (right/bottom).
285    End,
286    /// Distribute space evenly around each item.
287    SpaceAround,
288    /// Distribute space evenly between items (no outer space).
289    SpaceBetween,
290}
291
292/// How a layout container handles content that exceeds available space.
293///
294/// This enum models the CSS `overflow` property for terminal layouts.
295/// The actual clipping or scrolling is performed by the render layer;
296/// this value acts as a declarative hint attached to [`Flex`] or [`Grid`]
297/// so that widgets and the renderer know how to treat overflow regions.
298///
299/// # Migration rationale
300///
301/// Web components routinely set `overflow: hidden`, `overflow: scroll`, etc.
302/// Without an explicit model the migration code emitter cannot faithfully
303/// translate these semantics. This enum bridges that gap.
304#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
305pub enum OverflowBehavior {
306    /// Content that exceeds the container is clipped at the boundary.
307    /// This is the safe default for terminals where drawing outside
308    /// an allocated region corrupts neighbouring widgets.
309    #[default]
310    Clip,
311    /// Content is allowed to overflow visually (useful for popovers,
312    /// tooltips, and hit-test regions that extend beyond their container).
313    Visible,
314    /// Content is clipped but a scrollbar region is reserved.
315    /// The `max_content` field, when set, tells the scrollbar how
316    /// large the virtual content area is.
317    Scroll {
318        /// Size of the virtual content area in the overflow direction.
319        /// `None` means "determine from content measurement".
320        max_content: Option<u16>,
321    },
322    /// Items that don't fit are wrapped to the next row/column.
323    /// Only meaningful for [`Flex`] containers.
324    Wrap,
325}
326
327/// Responsive breakpoint tiers for terminal widths.
328///
329/// Ordered from smallest to largest. Each variant represents a width
330/// range determined by [`Breakpoints`].
331///
332/// | Breakpoint | Default Min Width | Typical Use               |
333/// |-----------|-------------------|---------------------------|
334/// | `Xs`      | < 60 cols         | Minimal / ultra-narrow    |
335/// | `Sm`      | 60–89 cols        | Compact layouts           |
336/// | `Md`      | 90–119 cols       | Standard terminal width   |
337/// | `Lg`      | 120–159 cols      | Wide terminals            |
338/// | `Xl`      | 160+ cols         | Ultra-wide / tiled        |
339#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
340pub enum Breakpoint {
341    /// Extra small: narrowest tier.
342    Xs,
343    /// Small: compact layouts.
344    Sm,
345    /// Medium: standard terminal width.
346    Md,
347    /// Large: wide terminals.
348    Lg,
349    /// Extra large: ultra-wide or tiled layouts.
350    Xl,
351}
352
353impl Breakpoint {
354    /// All breakpoints in ascending order.
355    pub const ALL: [Breakpoint; 5] = [
356        Breakpoint::Xs,
357        Breakpoint::Sm,
358        Breakpoint::Md,
359        Breakpoint::Lg,
360        Breakpoint::Xl,
361    ];
362
363    /// Ordinal index (0–4).
364    #[inline]
365    const fn index(self) -> u8 {
366        match self {
367            Breakpoint::Xs => 0,
368            Breakpoint::Sm => 1,
369            Breakpoint::Md => 2,
370            Breakpoint::Lg => 3,
371            Breakpoint::Xl => 4,
372        }
373    }
374
375    /// Short label for display.
376    #[must_use]
377    pub const fn label(self) -> &'static str {
378        match self {
379            Breakpoint::Xs => "xs",
380            Breakpoint::Sm => "sm",
381            Breakpoint::Md => "md",
382            Breakpoint::Lg => "lg",
383            Breakpoint::Xl => "xl",
384        }
385    }
386}
387
388impl std::fmt::Display for Breakpoint {
389    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
390        f.write_str(self.label())
391    }
392}
393
394/// Breakpoint thresholds for responsive layouts.
395///
396/// Each field is the minimum width (in terminal columns) for that breakpoint.
397/// Xs implicitly starts at width 0.
398#[derive(Debug, Clone, Copy, PartialEq, Eq)]
399pub struct Breakpoints {
400    /// Minimum width for Sm.
401    pub sm: u16,
402    /// Minimum width for Md.
403    pub md: u16,
404    /// Minimum width for Lg.
405    pub lg: u16,
406    /// Minimum width for Xl.
407    pub xl: u16,
408}
409
410impl Breakpoints {
411    /// Default breakpoints: 60 / 90 / 120 / 160 columns.
412    pub const DEFAULT: Self = Self {
413        sm: 60,
414        md: 90,
415        lg: 120,
416        xl: 160,
417    };
418
419    /// Create breakpoints with explicit thresholds.
420    ///
421    /// Values are sanitized to be monotonically non-decreasing.
422    pub const fn new(sm: u16, md: u16, lg: u16) -> Self {
423        let md = if md < sm { sm } else { md };
424        let lg = if lg < md { md } else { lg };
425        // Default xl to lg + 40 if not specified via new_with_xl.
426        let xl = match lg.checked_add(40) {
427            Some(v) => v,
428            None => u16::MAX,
429        };
430        Self { sm, md, lg, xl }
431    }
432
433    /// Create breakpoints with all four explicit thresholds.
434    ///
435    /// Values are sanitized to be monotonically non-decreasing.
436    pub const fn new_with_xl(sm: u16, md: u16, lg: u16, xl: u16) -> Self {
437        let md = if md < sm { sm } else { md };
438        let lg = if lg < md { md } else { lg };
439        let xl = if xl < lg { lg } else { xl };
440        Self { sm, md, lg, xl }
441    }
442
443    /// Classify a width into a breakpoint bucket.
444    #[inline]
445    pub const fn classify_width(self, width: u16) -> Breakpoint {
446        if width >= self.xl {
447            Breakpoint::Xl
448        } else if width >= self.lg {
449            Breakpoint::Lg
450        } else if width >= self.md {
451            Breakpoint::Md
452        } else if width >= self.sm {
453            Breakpoint::Sm
454        } else {
455            Breakpoint::Xs
456        }
457    }
458
459    /// Classify a Size (uses width).
460    #[inline]
461    pub const fn classify_size(self, size: Size) -> Breakpoint {
462        self.classify_width(size.width)
463    }
464
465    /// Check if width is at least a given breakpoint.
466    #[inline]
467    pub const fn at_least(self, width: u16, min: Breakpoint) -> bool {
468        self.classify_width(width).index() >= min.index()
469    }
470
471    /// Check if width is between two breakpoints (inclusive).
472    #[inline]
473    pub const fn between(self, width: u16, min: Breakpoint, max: Breakpoint) -> bool {
474        let idx = self.classify_width(width).index();
475        idx >= min.index() && idx <= max.index()
476    }
477
478    /// Get the minimum width threshold for a given breakpoint.
479    #[must_use]
480    pub const fn threshold(self, bp: Breakpoint) -> u16 {
481        match bp {
482            Breakpoint::Xs => 0,
483            Breakpoint::Sm => self.sm,
484            Breakpoint::Md => self.md,
485            Breakpoint::Lg => self.lg,
486            Breakpoint::Xl => self.xl,
487        }
488    }
489
490    /// Get all thresholds as `(Breakpoint, min_width)` pairs.
491    #[must_use]
492    pub const fn thresholds(self) -> [(Breakpoint, u16); 5] {
493        [
494            (Breakpoint::Xs, 0),
495            (Breakpoint::Sm, self.sm),
496            (Breakpoint::Md, self.md),
497            (Breakpoint::Lg, self.lg),
498            (Breakpoint::Xl, self.xl),
499        ]
500    }
501}
502
503/// Size negotiation hints for layout.
504#[derive(Debug, Clone, Copy, Default)]
505pub struct Measurement {
506    /// Minimum width in columns.
507    pub min_width: u16,
508    /// Minimum height in rows.
509    pub min_height: u16,
510    /// Maximum width (None = unbounded).
511    pub max_width: Option<u16>,
512    /// Maximum height (None = unbounded).
513    pub max_height: Option<u16>,
514}
515
516impl Measurement {
517    /// Create a fixed-size measurement (min == max).
518    #[must_use]
519    pub fn fixed(width: u16, height: u16) -> Self {
520        Self {
521            min_width: width,
522            min_height: height,
523            max_width: Some(width),
524            max_height: Some(height),
525        }
526    }
527
528    /// Create a flexible measurement with minimum size and no maximum.
529    #[must_use]
530    pub fn flexible(min_width: u16, min_height: u16) -> Self {
531        Self {
532            min_width,
533            min_height,
534            max_width: None,
535            max_height: None,
536        }
537    }
538}
539
540/// A flexible layout container.
541#[derive(Debug, Clone, Default)]
542pub struct Flex {
543    direction: Direction,
544    constraints: Constraints,
545    margin: Sides,
546    gap: u16,
547    alignment: Alignment,
548    flow_direction: direction::FlowDirection,
549    overflow: OverflowBehavior,
550}
551
552impl Flex {
553    /// Create a new vertical flex layout.
554    #[must_use]
555    pub fn vertical() -> Self {
556        Self {
557            direction: Direction::Vertical,
558            ..Default::default()
559        }
560    }
561
562    /// Create a new horizontal flex layout.
563    #[must_use]
564    pub fn horizontal() -> Self {
565        Self {
566            direction: Direction::Horizontal,
567            ..Default::default()
568        }
569    }
570
571    /// Set the layout direction.
572    #[must_use]
573    pub fn direction(mut self, direction: Direction) -> Self {
574        self.direction = direction;
575        self
576    }
577
578    /// Set the constraints.
579    #[must_use]
580    pub fn constraints(mut self, constraints: impl IntoIterator<Item = Constraint>) -> Self {
581        self.constraints = constraints.into_iter().collect();
582        self
583    }
584
585    /// Set the margin.
586    #[must_use]
587    pub fn margin(mut self, margin: Sides) -> Self {
588        self.margin = margin;
589        self
590    }
591
592    /// Set the gap between items.
593    #[must_use]
594    pub fn gap(mut self, gap: u16) -> Self {
595        self.gap = gap;
596        self
597    }
598
599    /// Set the alignment.
600    #[must_use]
601    pub fn alignment(mut self, alignment: Alignment) -> Self {
602        self.alignment = alignment;
603        self
604    }
605
606    /// Set the horizontal flow direction (LTR or RTL).
607    ///
608    /// When set to [`FlowDirection::Rtl`],
609    /// horizontal layouts are mirrored: the first child appears at the right
610    /// edge instead of the left. Vertical layouts are not affected.
611    #[must_use]
612    pub fn flow_direction(mut self, flow: direction::FlowDirection) -> Self {
613        self.flow_direction = flow;
614        self
615    }
616
617    /// Set the overflow behavior for this container.
618    #[must_use]
619    pub fn overflow(mut self, overflow: OverflowBehavior) -> Self {
620        self.overflow = overflow;
621        self
622    }
623
624    /// Get the current overflow behavior.
625    #[must_use]
626    pub fn overflow_behavior(&self) -> OverflowBehavior {
627        self.overflow
628    }
629
630    /// Number of constraints (and thus output rects from [`split`](Self::split)).
631    #[must_use]
632    pub fn constraint_count(&self) -> usize {
633        self.constraints.len()
634    }
635
636    /// Split the given area into smaller rectangles according to the configuration.
637    pub fn split(&self, area: Rect) -> Rects {
638        // Apply margin
639        let inner = area.inner(self.margin);
640        if inner.is_empty() {
641            return self.constraints.iter().map(|_| Rect::default()).collect();
642        }
643
644        let total_size = match self.direction {
645            Direction::Horizontal => inner.width,
646            Direction::Vertical => inner.height,
647        };
648
649        let count = self.constraints.len();
650        if count == 0 {
651            return Rects::new();
652        }
653
654        // Calculate gaps safely
655        let gap_count = count - 1;
656        let total_gap = (gap_count as u64 * self.gap as u64).min(u16::MAX as u64) as u16;
657        let available_size = total_size.saturating_sub(total_gap);
658
659        // Solve constraints to get sizes
660        let sizes = solve_constraints(&self.constraints, available_size);
661
662        // Convert sizes to rects
663        let mut rects = self.sizes_to_rects(inner, &sizes);
664
665        // Mirror horizontally for RTL horizontal layouts.
666        if self.flow_direction.is_rtl() && self.direction == Direction::Horizontal {
667            direction::mirror_rects_horizontal(&mut rects, inner);
668        }
669
670        rects
671    }
672
673    /// Split the given area into smaller rectangles allocated in `arena`,
674    /// avoiding heap allocations even when constraint count exceeds inline capacity
675    /// (`bd-g00-root-epic-ewths.31.3`).
676    pub fn split_in<'a>(&self, arena: &'a ftui_core::arena::FrameArena, area: Rect) -> &'a [Rect] {
677        let inner = area.inner(self.margin);
678        if inner.is_empty() {
679            let mut rects = arena.new_vec_with_capacity::<Rect>(self.constraints.len());
680            for _ in &self.constraints {
681                rects.push(Rect::default());
682            }
683            return rects.into_bump_slice();
684        }
685
686        let total_size = match self.direction {
687            Direction::Horizontal => inner.width,
688            Direction::Vertical => inner.height,
689        };
690
691        let count = self.constraints.len();
692        if count == 0 {
693            return &[];
694        }
695
696        let gap_count = count - 1;
697        let total_gap = (gap_count as u64 * self.gap as u64).min(u16::MAX as u64) as u16;
698        let available_size = total_size.saturating_sub(total_gap);
699
700        let mut sizes = arena.new_vec_with_capacity::<u16>(count);
701        sizes.resize(count, 0);
702        solve_constraints_with_hints_into(
703            &self.constraints,
704            available_size,
705            &|_, _| LayoutSizeHint::ZERO,
706            None,
707            &mut sizes,
708        );
709        let mut rects = self.sizes_to_rects_in(arena, inner, &sizes);
710
711        if self.flow_direction.is_rtl() && self.direction == Direction::Horizontal {
712            direction::mirror_rects_horizontal(&mut rects, inner);
713        }
714
715        rects.into_bump_slice()
716    }
717
718    fn sizes_to_rects(&self, area: Rect, sizes: &[u16]) -> Rects {
719        let mut rects = SmallVec::with_capacity(sizes.len());
720        self.populate_rects_from_sizes(area, sizes, |r| rects.push(r));
721        rects
722    }
723
724    fn sizes_to_rects_in<'a>(
725        &self,
726        arena: &'a ftui_core::arena::FrameArena,
727        area: Rect,
728        sizes: &[u16],
729    ) -> ftui_core::arena::BumpVec<'a, Rect> {
730        let mut rects = arena.new_vec_with_capacity::<Rect>(sizes.len());
731        self.populate_rects_from_sizes(area, sizes, |r| rects.push(r));
732        rects
733    }
734
735    fn populate_rects_from_sizes<P: FnMut(Rect)>(&self, area: Rect, sizes: &[u16], mut push: P) {
736        if sizes.is_empty() {
737            return;
738        }
739
740        let total_items_size: u16 = sizes.iter().fold(0u16, |acc, &s| acc.saturating_add(s));
741        let total_available = match self.direction {
742            Direction::Horizontal => area.width,
743            Direction::Vertical => area.height,
744        };
745
746        // Determine offsets strategy
747        let (start_shift, use_formula) = match self.alignment {
748            Alignment::Start => (0, None),
749            Alignment::End => {
750                let gap_space = (sizes.len().saturating_sub(1) as u64 * self.gap as u64)
751                    .min(u16::MAX as u64) as u16;
752                let used = total_items_size.saturating_add(gap_space);
753                (total_available.saturating_sub(used), None)
754            }
755            Alignment::Center => {
756                let gap_space = (sizes.len().saturating_sub(1) as u64 * self.gap as u64)
757                    .min(u16::MAX as u64) as u16;
758                let used = total_items_size.saturating_add(gap_space);
759                (total_available.saturating_sub(used) / 2, None)
760            }
761            Alignment::SpaceBetween => {
762                let gap_space = (sizes.len().saturating_sub(1) as u64 * self.gap as u64)
763                    .min(u16::MAX as u64) as u16;
764                let used = total_items_size.saturating_add(gap_space);
765                let leftover = total_available.saturating_sub(used);
766                let slots = sizes.len().saturating_sub(1);
767                if slots > 0 {
768                    (0, Some((leftover, slots, 0))) // 0 = Between
769                } else {
770                    (0, None)
771                }
772            }
773            Alignment::SpaceAround => {
774                let gap_space = (sizes.len().saturating_sub(1) as u64 * self.gap as u64)
775                    .min(u16::MAX as u64) as u16;
776                let used = total_items_size.saturating_add(gap_space);
777                let leftover = total_available.saturating_sub(used);
778                let slots = sizes.len() * 2;
779                if slots > 0 {
780                    (0, Some((leftover, slots, 1))) // 1 = Around
781                } else {
782                    (0, None)
783                }
784            }
785        };
786
787        let mut accumulated_size = 0;
788
789        for (i, &size) in sizes.iter().enumerate() {
790            let explicit_gap_so_far = if i > 0 {
791                (i as u64 * self.gap as u64).min(u16::MAX as u64) as u16
792            } else {
793                0
794            };
795
796            let gap_offset = if let Some((leftover, slots, mode)) = use_formula {
797                if mode == 0 {
798                    // Between: (Leftover * i) / slots + explicit gaps
799                    if i == 0 {
800                        0
801                    } else {
802                        explicit_gap_so_far
803                            .saturating_add((leftover as u64 * i as u64 / slots as u64) as u16)
804                    }
805                } else {
806                    // Around: nearest-integer rounding + explicit gaps
807                    let numerator = leftover as u64 * (2 * i as u64 + 1);
808                    let denominator = slots as u64;
809                    let raw = (numerator + (denominator / 2)) / denominator;
810                    explicit_gap_so_far.saturating_add(raw.min(u64::from(u16::MAX)) as u16)
811                }
812            } else {
813                // Fixed gap
814                explicit_gap_so_far
815            };
816
817            let pos = match self.direction {
818                Direction::Horizontal => area
819                    .x
820                    .saturating_add(start_shift)
821                    .saturating_add(accumulated_size)
822                    .saturating_add(gap_offset),
823                Direction::Vertical => area
824                    .y
825                    .saturating_add(start_shift)
826                    .saturating_add(accumulated_size)
827                    .saturating_add(gap_offset),
828            };
829
830            let rect = match self.direction {
831                Direction::Horizontal => Rect {
832                    x: pos,
833                    y: area.y,
834                    width: size.min(area.right().saturating_sub(pos)),
835                    height: area.height,
836                },
837                Direction::Vertical => Rect {
838                    x: area.x,
839                    y: pos,
840                    width: area.width,
841                    height: size.min(area.bottom().saturating_sub(pos)),
842                },
843            };
844            push(rect);
845            accumulated_size = accumulated_size.saturating_add(size);
846        }
847    }
848
849    /// Split area using intrinsic sizing from a measurer callback.
850    ///
851    /// This method enables content-aware layout with [`Constraint::FitContent`],
852    /// [`Constraint::FitContentBounded`], and [`Constraint::FitMin`].
853    ///
854    /// # Arguments
855    ///
856    /// - `area`: Available rectangle
857    /// - `measurer`: Callback that returns [`LayoutSizeHint`] for item at index
858    ///
859    /// # Example
860    ///
861    /// ```ignore
862    /// let flex = Flex::horizontal()
863    ///     .constraints([Constraint::FitContent, Constraint::Fill]);
864    ///
865    /// let rects = flex.split_with_measurer(area, |idx, available| {
866    ///     match idx {
867    ///         0 => LayoutSizeHint { min: 5, preferred: 20, max: None },
868    ///         _ => LayoutSizeHint::ZERO,
869    ///     }
870    /// });
871    /// ```
872    pub fn split_with_measurer<F>(&self, area: Rect, measurer: F) -> Rects
873    where
874        F: Fn(usize, u16) -> LayoutSizeHint,
875    {
876        // Apply margin
877        let inner = area.inner(self.margin);
878        if inner.is_empty() {
879            return self.constraints.iter().map(|_| Rect::default()).collect();
880        }
881
882        let total_size = match self.direction {
883            Direction::Horizontal => inner.width,
884            Direction::Vertical => inner.height,
885        };
886
887        let count = self.constraints.len();
888        if count == 0 {
889            return Rects::new();
890        }
891
892        // Calculate gaps safely
893        let gap_count = count - 1;
894        let total_gap = (gap_count as u64 * self.gap as u64).min(u16::MAX as u64) as u16;
895        let available_size = total_size.saturating_sub(total_gap);
896
897        // Solve constraints with hints from measurer
898        let sizes =
899            solve_constraints_with_hints(&self.constraints, available_size, &measurer, None);
900
901        // Convert sizes to rects
902        let mut rects = self.sizes_to_rects(inner, &sizes);
903
904        // Mirror horizontally for RTL horizontal layouts.
905        if self.flow_direction.is_rtl() && self.direction == Direction::Horizontal {
906            direction::mirror_rects_horizontal(&mut rects, inner);
907        }
908
909        rects
910    }
911
912    /// Arena-backed counterpart to [`split_with_measurer`](Self::split_with_measurer).
913    pub fn split_with_measurer_in<'a, F>(
914        &self,
915        arena: &'a ftui_core::arena::FrameArena,
916        area: Rect,
917        measurer: F,
918    ) -> &'a [Rect]
919    where
920        F: Fn(usize, u16) -> LayoutSizeHint,
921    {
922        let inner = area.inner(self.margin);
923        if inner.is_empty() {
924            let mut rects = arena.new_vec_with_capacity::<Rect>(self.constraints.len());
925            for _ in &self.constraints {
926                rects.push(Rect::default());
927            }
928            return rects.into_bump_slice();
929        }
930
931        let total_size = match self.direction {
932            Direction::Horizontal => inner.width,
933            Direction::Vertical => inner.height,
934        };
935
936        let count = self.constraints.len();
937        if count == 0 {
938            return &[];
939        }
940
941        let gap_count = count - 1;
942        let total_gap = (gap_count as u64 * self.gap as u64).min(u16::MAX as u64) as u16;
943        let available_size = total_size.saturating_sub(total_gap);
944
945        let mut sizes = arena.new_vec_with_capacity::<u16>(count);
946        sizes.resize(count, 0);
947        solve_constraints_with_hints_into(
948            &self.constraints,
949            available_size,
950            &measurer,
951            None,
952            &mut sizes,
953        );
954        let mut rects = self.sizes_to_rects_in(arena, inner, &sizes);
955
956        if self.flow_direction.is_rtl() && self.direction == Direction::Horizontal {
957            direction::mirror_rects_horizontal(&mut rects, inner);
958        }
959
960        rects.into_bump_slice()
961    }
962    /// Split area using intrinsic sizing and temporal coherence.
963    ///
964    /// Combines the content-aware sizing of [`split_with_measurer`](Self::split_with_measurer)
965    /// with stability across small geometry perturbations.
966    pub fn split_with_measurer_stably<F>(
967        &self,
968        area: Rect,
969        measurer: F,
970        cache: &mut CoherenceCache,
971    ) -> Rects
972    where
973        F: Fn(usize, u16) -> LayoutSizeHint,
974    {
975        // Apply margin
976        let inner = area.inner(self.margin);
977        if inner.is_empty() {
978            return self.constraints.iter().map(|_| Rect::default()).collect();
979        }
980
981        let total_size = match self.direction {
982            Direction::Horizontal => inner.width,
983            Direction::Vertical => inner.height,
984        };
985
986        let count = self.constraints.len();
987        if count == 0 {
988            return Rects::new();
989        }
990
991        // Calculate gaps safely
992        let gap_count = count - 1;
993        let total_gap = (gap_count as u64 * self.gap as u64).min(u16::MAX as u64) as u16;
994        let available_size = total_size.saturating_sub(total_gap);
995
996        // Solve constraints with hints and coherence
997        let id = CoherenceId::new(&self.constraints, self.direction);
998        let sizes = solve_constraints_with_hints(
999            &self.constraints,
1000            available_size,
1001            &measurer,
1002            Some((cache, id)),
1003        );
1004
1005        // Convert sizes to rects
1006        let mut rects = self.sizes_to_rects(inner, &sizes);
1007
1008        // Mirror horizontally for RTL horizontal layouts.
1009        if self.flow_direction.is_rtl() && self.direction == Direction::Horizontal {
1010            direction::mirror_rects_horizontal(&mut rects, inner);
1011        }
1012
1013        rects
1014    }
1015
1016    /// Arena-backed counterpart to [`split_with_measurer_stably`](Self::split_with_measurer_stably).
1017    pub fn split_with_measurer_stably_in<'a, F>(
1018        &self,
1019        arena: &'a ftui_core::arena::FrameArena,
1020        area: Rect,
1021        measurer: F,
1022        cache: &mut CoherenceCache,
1023    ) -> &'a [Rect]
1024    where
1025        F: Fn(usize, u16) -> LayoutSizeHint,
1026    {
1027        let inner = area.inner(self.margin);
1028        if inner.is_empty() {
1029            let mut rects = arena.new_vec_with_capacity::<Rect>(self.constraints.len());
1030            for _ in &self.constraints {
1031                rects.push(Rect::default());
1032            }
1033            return rects.into_bump_slice();
1034        }
1035
1036        let total_size = match self.direction {
1037            Direction::Horizontal => inner.width,
1038            Direction::Vertical => inner.height,
1039        };
1040
1041        let count = self.constraints.len();
1042        if count == 0 {
1043            return &[];
1044        }
1045
1046        let gap_count = count - 1;
1047        let total_gap = (gap_count as u64 * self.gap as u64).min(u16::MAX as u64) as u16;
1048        let available_size = total_size.saturating_sub(total_gap);
1049
1050        let id = CoherenceId::new(&self.constraints, self.direction);
1051        let mut sizes = arena.new_vec_with_capacity::<u16>(count);
1052        sizes.resize(count, 0);
1053        solve_constraints_with_hints_into(
1054            &self.constraints,
1055            available_size,
1056            &measurer,
1057            Some((cache, id)),
1058            &mut sizes,
1059        );
1060
1061        let mut rects = self.sizes_to_rects_in(arena, inner, &sizes);
1062
1063        if self.flow_direction.is_rtl() && self.direction == Direction::Horizontal {
1064            direction::mirror_rects_horizontal(&mut rects, inner);
1065        }
1066
1067        rects.into_bump_slice()
1068    }
1069}
1070
1071/// Solve 1D constraints to determine sizes.
1072///
1073/// This shared logic is used by both Flex and Grid layouts.
1074/// For intrinsic sizing support, use [`solve_constraints_with_hints`].
1075pub(crate) fn solve_constraints(constraints: &[Constraint], available_size: u16) -> Sizes {
1076    // Use the with_hints version with a no-op measurer and no coherence
1077    solve_constraints_with_hints(
1078        constraints,
1079        available_size,
1080        &|_, _| LayoutSizeHint::ZERO,
1081        None,
1082    )
1083}
1084
1085/// Solve 1D constraints with intrinsic sizing support.
1086///
1087/// The measurer callback provides size hints for FitContent, FitContentBounded, and FitMin
1088/// constraints. It receives the constraint index and remaining available space.
1089pub(crate) fn solve_constraints_with_hints<F>(
1090    constraints: &[Constraint],
1091    available_size: u16,
1092    measurer: &F,
1093    coherence: Option<(&mut CoherenceCache, CoherenceId)>,
1094) -> Sizes
1095where
1096    F: Fn(usize, u16) -> LayoutSizeHint,
1097{
1098    let mut sizes: Sizes = smallvec::smallvec![0u16; constraints.len()];
1099    solve_constraints_with_hints_into(constraints, available_size, measurer, coherence, &mut sizes);
1100    sizes
1101}
1102
1103pub(crate) fn solve_constraints_with_hints_into<F>(
1104    constraints: &[Constraint],
1105    available_size: u16,
1106    measurer: &F,
1107    mut coherence: Option<(&mut CoherenceCache, CoherenceId)>,
1108    sizes: &mut [u16],
1109) where
1110    F: Fn(usize, u16) -> LayoutSizeHint,
1111{
1112    const WEIGHT_SCALE: u64 = 10_000;
1113
1114    let mut remaining = available_size;
1115    let mut grow_indices: SmallVec<[usize; LAYOUT_INLINE_CAP]> = SmallVec::new();
1116
1117    let grow_weight = |constraint: Constraint| -> u64 {
1118        match constraint {
1119            Constraint::Min(_) | Constraint::Max(_) | Constraint::Fill => WEIGHT_SCALE,
1120            _ => 0,
1121        }
1122    };
1123
1124    // Pass 1: Allocate hard minimums (Fixed, Min, FitMin, FitContentBounded min).
1125    // These constraints are non-negotiable and take precedence over relative/soft constraints.
1126    for (i, &constraint) in constraints.iter().enumerate() {
1127        match constraint {
1128            Constraint::Fixed(size) => {
1129                let size = min(size, remaining);
1130                sizes[i] = size;
1131                remaining = remaining.saturating_sub(size);
1132            }
1133            Constraint::Min(min_size) => {
1134                let size = min(min_size, remaining);
1135                sizes[i] = size;
1136                remaining = remaining.saturating_sub(size);
1137                // Min will also be added to grow_indices in Pass 2
1138            }
1139            Constraint::FitMin => {
1140                let hint = measurer(i, remaining);
1141                let size = min(hint.min, remaining);
1142                sizes[i] = size;
1143                remaining = remaining.saturating_sub(size);
1144            }
1145            Constraint::FitContent => {
1146                let hint = measurer(i, remaining);
1147                let size = min(hint.min, remaining);
1148                sizes[i] = size;
1149                remaining = remaining.saturating_sub(size);
1150            }
1151            Constraint::FitContentBounded { min: min_bound, .. } => {
1152                // Reserve the minimum bound immediately
1153                let size = min(min_bound, remaining);
1154                sizes[i] = size;
1155                remaining = remaining.saturating_sub(size);
1156            }
1157            _ => {} // Soft constraints handled in Pass 2
1158        }
1159    }
1160
1161    // Pass 2: Allocate soft/relative constraints (Percentage, Ratio, FitContent preferred).
1162    // These fill remaining space after hard minimums.
1163    for (i, &constraint) in constraints.iter().enumerate() {
1164        match constraint {
1165            Constraint::Percentage(p) => {
1166                let target = (available_size as f32 * p / 100.0)
1167                    .round()
1168                    .min(u16::MAX as f32) as u16;
1169                let needed = target.saturating_sub(sizes[i]);
1170                let alloc = min(needed, remaining);
1171                sizes[i] = sizes[i].saturating_add(alloc);
1172                remaining = remaining.saturating_sub(alloc);
1173            }
1174            Constraint::Ratio(n, d) => {
1175                let target = if d == 0 {
1176                    0
1177                } else {
1178                    (u64::from(available_size) * u64::from(n) / u64::from(d)).min(u16::MAX as u64)
1179                        as u16
1180                };
1181                let needed = target.saturating_sub(sizes[i]);
1182                let alloc = min(needed, remaining);
1183                sizes[i] = sizes[i].saturating_add(alloc);
1184                remaining = remaining.saturating_sub(alloc);
1185            }
1186            Constraint::FitContent => {
1187                let hint = measurer(i, remaining);
1188                let preferred = hint
1189                    .preferred
1190                    .max(sizes[i])
1191                    .min(hint.max.unwrap_or(u16::MAX));
1192                let needed = preferred.saturating_sub(sizes[i]);
1193                let alloc = min(needed, remaining);
1194                sizes[i] = sizes[i].saturating_add(alloc);
1195                remaining = remaining.saturating_sub(alloc);
1196            }
1197            Constraint::FitContentBounded { max: max_bound, .. } => {
1198                let hint = measurer(i, remaining);
1199                let preferred = hint.preferred.max(sizes[i]).min(max_bound);
1200                let needed = preferred.saturating_sub(sizes[i]);
1201                let alloc = min(needed, remaining);
1202                sizes[i] = sizes[i].saturating_add(alloc);
1203                remaining = remaining.saturating_sub(alloc);
1204            }
1205            Constraint::Min(_) => {
1206                grow_indices.push(i);
1207            }
1208            Constraint::Max(_) => {
1209                grow_indices.push(i);
1210            }
1211            Constraint::Fill => {
1212                grow_indices.push(i);
1213            }
1214            _ => {} // Hard constraints handled in Pass 1
1215        }
1216    }
1217
1218    // 3. Iterative distribution to flexible constraints
1219    loop {
1220        if remaining == 0 || grow_indices.is_empty() {
1221            break;
1222        }
1223
1224        let mut total_weight = 0u128;
1225        for &i in &grow_indices {
1226            let weight = grow_weight(constraints[i]);
1227            if weight > 0 {
1228                total_weight = total_weight.saturating_add(u128::from(weight));
1229            }
1230        }
1231
1232        if total_weight == 0 {
1233            break;
1234        }
1235
1236        let space_to_distribute = remaining;
1237
1238        // Calculate float targets for fair distribution (Largest Remainder Method)
1239        let targets: SmallVec<[f64; LAYOUT_INLINE_CAP]> = grow_indices
1240            .iter()
1241            .map(|&i| {
1242                let weight = grow_weight(constraints[i]);
1243                (space_to_distribute as f64 * weight as f64) / total_weight as f64
1244            })
1245            .collect();
1246
1247        // Get previous allocation if coherence is enabled
1248        let prev_alloc = coherence
1249            .as_ref()
1250            .and_then(|(cache, id)| cache.get(id))
1251            .map(|full_prev| {
1252                // Extract only the shares for the current grow_indices
1253                grow_indices
1254                    .iter()
1255                    .map(|&i| full_prev.get(i).copied().unwrap_or(0))
1256                    .collect()
1257            });
1258
1259        // Distribute space with stable rounding to minimize jitter and error
1260        let distributed = round_layout_stable(&targets, space_to_distribute, prev_alloc);
1261
1262        // Check for Max constraint violations
1263        let mut violations: SmallVec<[usize; LAYOUT_INLINE_CAP]> = SmallVec::new();
1264        for (k, &i) in grow_indices.iter().enumerate() {
1265            if let Constraint::Max(max_val) = constraints[i]
1266                && sizes[i].saturating_add(distributed[k]) > max_val
1267            {
1268                violations.push(i);
1269            }
1270        }
1271
1272        if violations.is_empty() {
1273            // No violations, commit shares and exit
1274            for (k, &i) in grow_indices.iter().enumerate() {
1275                sizes[i] = sizes[i].saturating_add(distributed[k]);
1276            }
1277            if let Some((cache, id)) = coherence.as_mut() {
1278                // Store full-sized vector mapping constraint index -> share.
1279                // We must inflate the dense `distributed` vector to the sparse constraint space.
1280                if distributed.len() == targets.len() {
1281                    let mut full_shares: Sizes = smallvec::smallvec![0u16; constraints.len()];
1282                    for (k, &i) in grow_indices.iter().enumerate() {
1283                        full_shares[i] = distributed[k];
1284                    }
1285                    cache.store(*id, full_shares);
1286                }
1287            }
1288            break;
1289        }
1290
1291        // Handle violations: clamp to Max and remove from grow pool
1292        for i in violations {
1293            if let Constraint::Max(max_val) = constraints[i] {
1294                // Calculate how much space this item *actually* consumes from remaining
1295                // which is (max - current_size)
1296                let consumed = max_val.saturating_sub(sizes[i]);
1297                sizes[i] = max_val;
1298                remaining = remaining.saturating_sub(consumed);
1299
1300                // Remove from grow indices
1301                if let Some(pos) = grow_indices.iter().position(|&x| x == i) {
1302                    grow_indices.remove(pos);
1303                }
1304            }
1305        }
1306    }
1307}
1308
1309// ---------------------------------------------------------------------------
1310// Stable Layout Rounding: Min-Displacement with Temporal Coherence
1311// ---------------------------------------------------------------------------
1312
1313/// Previous frame's allocation, used as tie-breaker for temporal stability.
1314///
1315/// Pass `None` for the first frame or when no history is available.
1316/// When provided, the rounding algorithm prefers allocations that
1317/// minimize change from the previous frame, reducing visual jitter.
1318pub type PreviousAllocation = Option<Sizes>;
1319
1320/// Round real-valued layout targets to integer cells with exact sum conservation.
1321///
1322/// # Mathematical Model
1323///
1324/// Given real-valued targets `r_i` (from the constraint solver) and a required
1325/// integer total, find integer allocations `x_i` that:
1326///
1327/// ```text
1328/// minimize   Σ_i |x_i − r_i|  +  μ · Σ_i |x_i − x_i_prev|
1329/// subject to Σ_i x_i = total
1330///            x_i ≥ 0
1331/// ```
1332///
1333/// where `x_i_prev` is the previous frame's allocation and `μ` is the temporal
1334/// stability weight (default 0.1).
1335///
1336/// # Algorithm: Largest Remainder with Temporal Tie-Breaking
1337///
1338/// This uses a variant of the Largest Remainder Method (Hamilton's method),
1339/// which provides optimal bounded displacement (|x_i − r_i| < 1 for all i):
1340///
1341/// 1. **Floor phase**: Set `x_i = floor(r_i)` for each element.
1342/// 2. **Deficit**: Compute `D = total − Σ floor(r_i)` extra cells to distribute.
1343/// 3. **Priority sort**: Rank elements by remainder `r_i − floor(r_i)` (descending).
1344///    Break ties using a composite key:
1345///    a. Prefer elements where `x_i_prev = ceil(r_i)` (temporal stability).
1346///    b. Prefer elements with smaller index (determinism).
1347/// 4. **Distribute**: Award one extra cell to each of the top `D` elements.
1348///
1349/// # Properties
1350///
1351/// 1. **Sum conservation**: `Σ x_i = total` exactly (proven by construction).
1352/// 2. **Bounded displacement**: `|x_i − r_i| < 1` for all `i` (since each x_i
1353///    is either `floor(r_i)` or `ceil(r_i)`).
1354/// 3. **Deterministic**: Same inputs → identical outputs (temporal tie-break +
1355///    index tie-break provide total ordering).
1356/// 4. **Temporal coherence**: When targets change slightly, allocations tend to
1357///    stay the same (preferring the previous frame's rounding direction).
1358/// 5. **Optimal displacement**: Among all integer allocations summing to `total`
1359///    with `floor(r_i) ≤ x_i ≤ ceil(r_i)`, the Largest Remainder Method
1360///    minimizes total absolute displacement.
1361///
1362/// # Failure Modes
1363///
1364/// - **All-zero targets**: Returns all zeros. Harmless (empty layout).
1365/// - **Negative deficit**: Can occur if targets sum to less than `total` after
1366///   flooring. The algorithm handles this via the clamp in step 2.
1367/// - **Very large N**: O(N log N) due to sorting. Acceptable for typical
1368///   layout counts (< 100 items).
1369///
1370/// # Example
1371///
1372/// ```
1373/// use ftui_layout::round_layout_stable;
1374///
1375/// // Targets: [10.4, 20.6, 9.0] must sum to 40
1376/// let result = round_layout_stable(&[10.4, 20.6, 9.0], 40, None);
1377/// assert_eq!(result.iter().sum::<u16>(), 40);
1378/// // 10.4 → 10, 20.6 → 21, 9.0 → 9 = 40 ✓
1379/// assert_eq!(result.as_slice(), &[10, 21, 9]);
1380/// ```
1381pub fn round_layout_stable(targets: &[f64], total: u16, prev: PreviousAllocation) -> Sizes {
1382    let n = targets.len();
1383    if n == 0 {
1384        return Sizes::new();
1385    }
1386
1387    // Step 1: Floor all targets
1388    let floors: Sizes = targets
1389        .iter()
1390        .map(|&r| (r.max(0.0).floor() as u64).min(u16::MAX as u64) as u16)
1391        .collect();
1392
1393    let floor_sum: u64 = floors.iter().map(|&x| u64::from(x)).sum();
1394    let total_u64 = u64::from(total);
1395
1396    // Step 2: Compute deficit (extra cells to distribute)
1397    if floor_sum > total_u64 {
1398        return redistribute_overflow(&floors, total);
1399    }
1400
1401    let deficit = (total_u64 - floor_sum) as u16;
1402
1403    if deficit == 0 {
1404        // Exact fit — no rounding needed
1405        return floors;
1406    }
1407
1408    // Step 3: Compute remainders and build priority list
1409    let mut priority: SmallVec<[(usize, f64, bool); LAYOUT_INLINE_CAP]> = targets
1410        .iter()
1411        .enumerate()
1412        .map(|(i, &r)| {
1413            // Sanitize non-finite targets (NaN/inf): NaN.max(0.0) already
1414            // floors to 0 above; a NaN remainder here would poison the sort.
1415            let raw_remainder = r - (floors[i] as f64);
1416            let remainder = if raw_remainder.is_finite() {
1417                raw_remainder
1418            } else {
1419                0.0
1420            };
1421            let ceil_val = floors[i].saturating_add(1);
1422            // Temporal stability: did previous allocation use ceil?
1423            let prev_used_ceil = prev
1424                .as_ref()
1425                .is_some_and(|p| p.get(i).copied() == Some(ceil_val));
1426            (i, remainder, prev_used_ceil)
1427        })
1428        .collect();
1429
1430    // Sort by: remainder descending, then temporal preference, then index ascending.
1431    // total_cmp keeps the comparator a TOTAL order: the previous
1432    // partial_cmp().unwrap_or(Equal) made NaN compare Equal to everything
1433    // while real values still ordered — an intransitive comparator that
1434    // std's sort is documented to panic on.
1435    priority.sort_by(|a, b| {
1436        b.1.total_cmp(&a.1)
1437            .then_with(|| {
1438                // Prefer items where prev used ceil (true > false)
1439                b.2.cmp(&a.2)
1440            })
1441            .then_with(|| {
1442                // Deterministic tie-break: smaller index first
1443                a.0.cmp(&b.0)
1444            })
1445    });
1446
1447    // Step 4: Distribute deficit
1448    let mut result = floors;
1449    let mut remaining_deficit = deficit;
1450
1451    // We award at most one extra cell per item to maintain the invariant
1452    // |x_i - r_i| < 1 (bounded displacement). Hamilton's method only
1453    // handles D < n. If D >= n, it implies sum(floors) + n <= total,
1454    // which means sum(targets) was significantly less than total.
1455    // In this case, we distribute the surplus as evenly as possible.
1456    if remaining_deficit as usize >= n {
1457        let per_item = remaining_deficit / (n as u16);
1458        for val in result.iter_mut() {
1459            *val = val.saturating_add(per_item);
1460        }
1461        remaining_deficit %= n as u16;
1462    }
1463
1464    if remaining_deficit > 0 {
1465        for &(i, _, _) in priority.iter().take(remaining_deficit as usize) {
1466            result[i] = result[i].saturating_add(1);
1467        }
1468    }
1469
1470    result
1471}
1472
1473/// Handle the edge case where floored values exceed total.
1474///
1475/// This can happen with very small totals and many items. We greedily
1476/// reduce the largest items by 1 until the sum matches.
1477fn redistribute_overflow(floors: &[u16], total: u16) -> Sizes {
1478    let mut result: Sizes = floors.iter().copied().collect();
1479    let current_sum: u64 = result.iter().map(|&x| u64::from(x)).sum();
1480    let total_u64 = u64::from(total);
1481    let n = result.len();
1482
1483    if current_sum <= total_u64 || n == 0 {
1484        return result;
1485    }
1486
1487    let mut overflow = current_sum - total_u64;
1488
1489    while overflow > 0 {
1490        let &max_val = result.iter().max().unwrap_or(&0);
1491        if max_val == 0 {
1492            // Cannot reduce further, even though overflow persists.
1493            // This happens if total < 0 (impossible for u16) or some other
1494            // degenerate state. Force sum to 0.
1495            for val in result.iter_mut() {
1496                *val = 0;
1497            }
1498            break;
1499        }
1500
1501        let count_max = result.iter().filter(|&&v| v == max_val).count() as u64;
1502        let &next_max = result.iter().filter(|&&v| v < max_val).max().unwrap_or(&0);
1503
1504        let delta = (max_val - next_max) as u64;
1505        let required_per_item = overflow.div_ceil(count_max);
1506        let reduce_per_item = delta.min(required_per_item).max(1) as u16;
1507
1508        let mut reduced_any = false;
1509        for val in result.iter_mut() {
1510            if *val == max_val {
1511                let amount = u64::from(*val)
1512                    .min(u64::from(reduce_per_item))
1513                    .min(overflow) as u16;
1514                if amount > 0 {
1515                    *val -= amount;
1516                    overflow -= u64::from(amount);
1517                    reduced_any = true;
1518                }
1519                if overflow == 0 {
1520                    break;
1521                }
1522            }
1523        }
1524
1525        if !reduced_any {
1526            // Hard fallback: should not happen if max_val > 0.
1527            for val in result.iter_mut() {
1528                if overflow == 0 {
1529                    break;
1530                }
1531                if *val > 0 {
1532                    *val -= 1;
1533                    overflow -= 1;
1534                }
1535            }
1536            break;
1537        }
1538    }
1539
1540    result
1541}
1542
1543#[cfg(test)]
1544mod tests {
1545    use super::*;
1546
1547    #[test]
1548    fn an_oversubscribed_row_shrinks_rather_than_overlapping() {
1549        // Min beside Fixed, asked for more than the row has. The solver gives
1550        // the minimum to the first and the remainder to the second: the rects
1551        // stay disjoint and inside the row, and it is the *caller* who has to
1552        // decide whether a column that small is still worth drawing into.
1553        for width in [120u16, 43, 42, 38, 20] {
1554            let rects = Flex::horizontal()
1555                .constraints([Constraint::Min(11), Constraint::Fixed(32)])
1556                .split(Rect::new(0, 0, width, 3));
1557            let total: u32 = rects.iter().map(|r| u32::from(r.width)).sum();
1558            assert_eq!(total, u32::from(width), "row {width} not fully used");
1559            assert!(
1560                rects.windows(2).all(|w| w[0].x + w[0].width <= w[1].x),
1561                "rects overlap at width {width}: {rects:?}"
1562            );
1563            assert!(
1564                rects
1565                    .iter()
1566                    .all(|r| u32::from(r.x) + u32::from(r.width) <= u32::from(width)),
1567                "rect past the end at width {width}: {rects:?}"
1568            );
1569        }
1570    }
1571
1572    #[test]
1573    fn round_layout_stable_nan_targets_do_not_panic_the_sort() {
1574        // Regression: NaN remainders made the priority comparator
1575        // intransitive (NaN Equal to everything while real values still
1576        // ordered); std's sort is documented to panic on non-total orders.
1577        // Large-ish N to engage the driftsort merge paths.
1578        let mut targets: Vec<f64> = (0..64).map(|i| (i as f64) * 0.37 + 0.1).collect();
1579        targets[7] = f64::NAN;
1580        targets[23] = f64::INFINITY;
1581        targets[41] = f64::NEG_INFINITY;
1582
1583        // The invariant under test is "no panic": the sort must stay a
1584        // total order in the presence of non-finite remainders.
1585        let sizes = round_layout_stable(&targets, 120, None);
1586        assert_eq!(sizes.len(), 64);
1587
1588        // And with only-NaN targets, all floors are 0 and the deficit path
1589        // still distributes exactly the requested total.
1590        let nan_targets = [f64::NAN; 8];
1591        let sizes = round_layout_stable(&nan_targets, 40, None);
1592        let sum: u64 = sizes.iter().map(|&x| u64::from(x)).sum();
1593        assert_eq!(sum, 40);
1594    }
1595
1596    #[test]
1597    fn fixed_split() {
1598        let flex = Flex::horizontal().constraints([Constraint::Fixed(10), Constraint::Fixed(20)]);
1599        let rects = flex.split(Rect::new(0, 0, 100, 10));
1600        assert_eq!(rects.len(), 2);
1601        assert_eq!(rects[0], Rect::new(0, 0, 10, 10));
1602        assert_eq!(rects[1], Rect::new(10, 0, 20, 10)); // Gap is 0 by default
1603    }
1604
1605    #[test]
1606    fn percentage_split() {
1607        let flex = Flex::horizontal()
1608            .constraints([Constraint::Percentage(50.0), Constraint::Percentage(50.0)]);
1609        let rects = flex.split(Rect::new(0, 0, 100, 10));
1610        assert_eq!(rects[0].width, 50);
1611        assert_eq!(rects[1].width, 50);
1612    }
1613
1614    #[test]
1615    fn gap_handling() {
1616        let flex = Flex::horizontal()
1617            .gap(5)
1618            .constraints([Constraint::Fixed(10), Constraint::Fixed(10)]);
1619        let rects = flex.split(Rect::new(0, 0, 100, 10));
1620        // Item 1: 0..10
1621        // Gap: 10..15
1622        // Item 2: 15..25
1623        assert_eq!(rects[0], Rect::new(0, 0, 10, 10));
1624        assert_eq!(rects[1], Rect::new(15, 0, 10, 10));
1625    }
1626
1627    #[test]
1628    fn mixed_constraints() {
1629        let flex = Flex::horizontal().constraints([
1630            Constraint::Fixed(10),
1631            Constraint::Min(10), // Should take half of remaining (90/2 = 45) + base 10? No, logic is simplified.
1632            Constraint::Percentage(10.0), // 10% of 100 = 10
1633        ]);
1634
1635        // Available: 100
1636        // Fixed(10) -> 10. Rem: 90.
1637        // Percent(10%) -> 10. Rem: 80.
1638        // Min(10) -> 10. Rem: 70.
1639        // Grow candidates: Min(10).
1640        // Distribute 70 to Min(10). Size = 10 + 70 = 80.
1641
1642        let rects = flex.split(Rect::new(0, 0, 100, 1));
1643        assert_eq!(rects[0].width, 10); // Fixed
1644        assert_eq!(rects[2].width, 10); // Percent
1645        assert_eq!(rects[1].width, 80); // Min + Remainder
1646    }
1647
1648    #[test]
1649    fn measurement_fixed_constraints() {
1650        let fixed = Measurement::fixed(5, 7);
1651        assert_eq!(fixed.min_width, 5);
1652        assert_eq!(fixed.min_height, 7);
1653        assert_eq!(fixed.max_width, Some(5));
1654        assert_eq!(fixed.max_height, Some(7));
1655    }
1656
1657    #[test]
1658    fn measurement_flexible_constraints() {
1659        let flexible = Measurement::flexible(2, 3);
1660        assert_eq!(flexible.min_width, 2);
1661        assert_eq!(flexible.min_height, 3);
1662        assert_eq!(flexible.max_width, None);
1663        assert_eq!(flexible.max_height, None);
1664    }
1665
1666    #[test]
1667    fn breakpoints_classify_defaults() {
1668        let bp = Breakpoints::DEFAULT;
1669        assert_eq!(bp.classify_width(20), Breakpoint::Xs);
1670        assert_eq!(bp.classify_width(60), Breakpoint::Sm);
1671        assert_eq!(bp.classify_width(90), Breakpoint::Md);
1672        assert_eq!(bp.classify_width(120), Breakpoint::Lg);
1673    }
1674
1675    #[test]
1676    fn breakpoints_at_least_and_between() {
1677        let bp = Breakpoints::new(50, 80, 110);
1678        assert!(bp.at_least(85, Breakpoint::Sm));
1679        assert!(bp.between(85, Breakpoint::Sm, Breakpoint::Md));
1680        assert!(!bp.between(85, Breakpoint::Lg, Breakpoint::Lg));
1681    }
1682
1683    #[test]
1684    fn alignment_end() {
1685        let flex = Flex::horizontal()
1686            .alignment(Alignment::End)
1687            .constraints([Constraint::Fixed(10), Constraint::Fixed(10)]);
1688        let rects = flex.split(Rect::new(0, 0, 100, 10));
1689        // Items should be pushed to the end: leftover = 100 - 20 = 80
1690        assert_eq!(rects[0], Rect::new(80, 0, 10, 10));
1691        assert_eq!(rects[1], Rect::new(90, 0, 10, 10));
1692    }
1693
1694    #[test]
1695    fn alignment_center() {
1696        let flex = Flex::horizontal()
1697            .alignment(Alignment::Center)
1698            .constraints([Constraint::Fixed(20), Constraint::Fixed(20)]);
1699        let rects = flex.split(Rect::new(0, 0, 100, 10));
1700        // Items should be centered: leftover = 100 - 40 = 60, offset = 30
1701        assert_eq!(rects[0], Rect::new(30, 0, 20, 10));
1702        assert_eq!(rects[1], Rect::new(50, 0, 20, 10));
1703    }
1704
1705    #[test]
1706    fn alignment_space_between() {
1707        let flex = Flex::horizontal()
1708            .alignment(Alignment::SpaceBetween)
1709            .constraints([
1710                Constraint::Fixed(10),
1711                Constraint::Fixed(10),
1712                Constraint::Fixed(10),
1713            ]);
1714        let rects = flex.split(Rect::new(0, 0, 100, 10));
1715        // Items: 30 total, leftover = 70, 2 gaps, 35 per gap
1716        assert_eq!(rects[0].x, 0);
1717        assert_eq!(rects[1].x, 45); // 10 + 35
1718        assert_eq!(rects[2].x, 90); // 45 + 10 + 35
1719    }
1720
1721    #[test]
1722    fn vertical_alignment() {
1723        let flex = Flex::vertical()
1724            .alignment(Alignment::End)
1725            .constraints([Constraint::Fixed(5), Constraint::Fixed(5)]);
1726        let rects = flex.split(Rect::new(0, 0, 10, 100));
1727        // Vertical: leftover = 100 - 10 = 90
1728        assert_eq!(rects[0], Rect::new(0, 90, 10, 5));
1729        assert_eq!(rects[1], Rect::new(0, 95, 10, 5));
1730    }
1731
1732    #[test]
1733    fn nested_flex_support() {
1734        // Outer horizontal split
1735        let outer = Flex::horizontal()
1736            .constraints([Constraint::Percentage(50.0), Constraint::Percentage(50.0)]);
1737        let outer_rects = outer.split(Rect::new(0, 0, 100, 100));
1738
1739        // Inner vertical split on the first half
1740        let inner = Flex::vertical().constraints([Constraint::Fixed(30), Constraint::Min(10)]);
1741        let inner_rects = inner.split(outer_rects[0]);
1742
1743        assert_eq!(inner_rects[0], Rect::new(0, 0, 50, 30));
1744        assert_eq!(inner_rects[1], Rect::new(0, 30, 50, 70));
1745    }
1746
1747    // Property-like invariant tests
1748    #[test]
1749    fn invariant_total_size_does_not_exceed_available() {
1750        // Test that constraint solving never allocates more than available
1751        for total in [10u16, 50, 100, 255] {
1752            let flex = Flex::horizontal().constraints([
1753                Constraint::Fixed(30),
1754                Constraint::Percentage(50.0),
1755                Constraint::Min(20),
1756            ]);
1757            let rects = flex.split(Rect::new(0, 0, total, 10));
1758            let total_width: u16 = rects.iter().map(|r| r.width).sum();
1759            assert!(
1760                total_width <= total,
1761                "Total width {} exceeded available {} for constraints",
1762                total_width,
1763                total
1764            );
1765        }
1766    }
1767
1768    #[test]
1769    fn invariant_empty_area_produces_empty_rects() {
1770        let flex = Flex::horizontal().constraints([Constraint::Fixed(10), Constraint::Fixed(10)]);
1771        let rects = flex.split(Rect::new(0, 0, 0, 0));
1772        assert!(rects.iter().all(|r| r.is_empty()));
1773    }
1774
1775    #[test]
1776    fn invariant_no_constraints_produces_empty_vec() {
1777        let flex = Flex::horizontal().constraints([]);
1778        let rects = flex.split(Rect::new(0, 0, 100, 100));
1779        assert!(rects.is_empty());
1780    }
1781
1782    #[test]
1783    fn flex_constraints_stay_inline_for_common_layouts() {
1784        let flex = Flex::horizontal().constraints([Constraint::Fixed(1); LAYOUT_INLINE_CAP]);
1785        assert_eq!(flex.constraint_count(), LAYOUT_INLINE_CAP);
1786        assert!(!flex.constraints.spilled());
1787
1788        let rects = flex.split(Rect::new(0, 0, LAYOUT_INLINE_CAP as u16, 1));
1789        assert_eq!(rects.len(), LAYOUT_INLINE_CAP);
1790        assert!(rects.iter().all(|rect| rect.width == 1));
1791    }
1792
1793    // --- Ratio constraint ---
1794
1795    #[test]
1796    fn ratio_constraint_splits_proportionally() {
1797        let flex =
1798            Flex::horizontal().constraints([Constraint::Ratio(1, 3), Constraint::Ratio(2, 3)]);
1799        let rects = flex.split(Rect::new(0, 0, 90, 10));
1800        assert_eq!(rects[0].width, 30);
1801        assert_eq!(rects[1].width, 60);
1802    }
1803
1804    #[test]
1805    fn ratio_constraint_with_zero_denominator() {
1806        // Zero denominator should not panic (max(1) guard)
1807        let flex = Flex::horizontal().constraints([Constraint::Ratio(1, 0)]);
1808        let rects = flex.split(Rect::new(0, 0, 100, 10));
1809        assert_eq!(rects.len(), 1);
1810    }
1811
1812    #[test]
1813    fn ratio_is_absolute_fraction() {
1814        let area = Rect::new(0, 0, 100, 1);
1815
1816        // Percentage is absolute against the total available.
1817        let rects = Flex::horizontal()
1818            .constraints([Constraint::Percentage(25.0)])
1819            .split(area);
1820        assert_eq!(rects[0].width, 25);
1821
1822        // Ratio(1, 4) should also be absolute (25% of 100 = 25).
1823        // It does NOT grow to fill remaining space.
1824        let rects = Flex::horizontal()
1825            .constraints([Constraint::Ratio(1, 4)])
1826            .split(area);
1827        assert_eq!(rects[0].width, 25);
1828    }
1829
1830    #[test]
1831    fn ratio_is_independent_of_grow_items() {
1832        let area = Rect::new(0, 0, 100, 1);
1833
1834        // Ratio(1, 4) takes 25 fixed. Fill takes remaining 75.
1835        let rects = Flex::horizontal()
1836            .constraints([Constraint::Ratio(1, 4), Constraint::Fill])
1837            .split(area);
1838        assert_eq!(rects[0].width, 25);
1839        assert_eq!(rects[1].width, 75);
1840    }
1841
1842    #[test]
1843    fn ratio_zero_numerator_should_be_zero() {
1844        // Ratio(0, 1) should logically get 0 space.
1845        // Test with Fill first to expose "last item gets remainder" logic artifact
1846        let flex = Flex::horizontal().constraints([Constraint::Fill, Constraint::Ratio(0, 1)]);
1847        let rects = flex.split(Rect::new(0, 0, 100, 1));
1848
1849        // Fill should get 100, Ratio should get 0
1850        assert_eq!(rects[0].width, 100, "Fill should take all space");
1851        assert_eq!(rects[1].width, 0, "Ratio(0, 1) should be width 0");
1852    }
1853
1854    // --- Max constraint ---
1855
1856    #[test]
1857    fn max_constraint_clamps_size() {
1858        let flex = Flex::horizontal().constraints([Constraint::Max(20), Constraint::Fixed(30)]);
1859        let rects = flex.split(Rect::new(0, 0, 100, 10));
1860        assert!(rects[0].width <= 20);
1861        assert_eq!(rects[1].width, 30);
1862    }
1863
1864    #[test]
1865    fn percentage_rounding_never_exceeds_available() {
1866        let constraints = [
1867            Constraint::Percentage(33.4),
1868            Constraint::Percentage(33.3),
1869            Constraint::Percentage(33.3),
1870        ];
1871        let sizes = solve_constraints(&constraints, 7);
1872        let total: u16 = sizes.iter().sum();
1873        assert!(total <= 7, "percent rounding overflowed: {sizes:?}");
1874        assert!(sizes.iter().all(|size| *size <= 7));
1875    }
1876
1877    #[test]
1878    fn tiny_area_saturates_fixed_and_min() {
1879        let constraints = [Constraint::Fixed(5), Constraint::Min(3), Constraint::Max(2)];
1880        let sizes = solve_constraints(&constraints, 2);
1881        assert_eq!(sizes[0], 2);
1882        assert_eq!(sizes[1], 0);
1883        assert_eq!(sizes[2], 0);
1884        assert_eq!(sizes.iter().sum::<u16>(), 2);
1885    }
1886
1887    #[test]
1888    fn ratio_distribution_sums_to_available() {
1889        // Since Ratio is absolute, 1/3 of 5 is 1, and 2/3 of 5 is 3.
1890        let constraints = [Constraint::Ratio(1, 3), Constraint::Ratio(2, 3)];
1891        let sizes = solve_constraints(&constraints, 5);
1892        assert_eq!(sizes.iter().sum::<u16>(), 4);
1893        assert_eq!(sizes[0], 1);
1894        assert_eq!(sizes[1], 3);
1895    }
1896
1897    #[test]
1898    fn flex_gap_exceeds_area_yields_zero_widths() {
1899        let flex = Flex::horizontal()
1900            .gap(5)
1901            .constraints([Constraint::Fixed(1), Constraint::Fixed(1)]);
1902        let rects = flex.split(Rect::new(0, 0, 3, 1));
1903        assert_eq!(rects.len(), 2);
1904        assert_eq!(rects[0].width, 0);
1905        assert_eq!(rects[1].width, 0);
1906    }
1907
1908    // --- SpaceAround alignment ---
1909
1910    #[test]
1911    fn alignment_space_around() {
1912        let flex = Flex::horizontal()
1913            .alignment(Alignment::SpaceAround)
1914            .constraints([Constraint::Fixed(10), Constraint::Fixed(10)]);
1915        let rects = flex.split(Rect::new(0, 0, 100, 10));
1916
1917        // SpaceAround: leftover = 80, space_unit = 80/(2*2) = 20
1918        // First item starts at 20, second at 20+10+40=70
1919        assert_eq!(rects[0].x, 20);
1920        assert_eq!(rects[1].x, 70);
1921    }
1922
1923    // --- Vertical with gap ---
1924
1925    #[test]
1926    fn vertical_gap() {
1927        let flex = Flex::vertical()
1928            .gap(5)
1929            .constraints([Constraint::Fixed(10), Constraint::Fixed(10)]);
1930        let rects = flex.split(Rect::new(0, 0, 50, 100));
1931        assert_eq!(rects[0], Rect::new(0, 0, 50, 10));
1932        assert_eq!(rects[1], Rect::new(0, 15, 50, 10));
1933    }
1934
1935    // --- Vertical center alignment ---
1936
1937    #[test]
1938    fn vertical_center() {
1939        let flex = Flex::vertical()
1940            .alignment(Alignment::Center)
1941            .constraints([Constraint::Fixed(10)]);
1942        let rects = flex.split(Rect::new(0, 0, 50, 100));
1943        // leftover = 90, offset = 45
1944        assert_eq!(rects[0].y, 45);
1945        assert_eq!(rects[0].height, 10);
1946    }
1947
1948    // --- Single constraint gets all space ---
1949
1950    #[test]
1951    fn single_min_takes_all() {
1952        let flex = Flex::horizontal().constraints([Constraint::Min(5)]);
1953        let rects = flex.split(Rect::new(0, 0, 80, 24));
1954        assert_eq!(rects[0].width, 80);
1955    }
1956
1957    // --- Fixed exceeds available ---
1958
1959    #[test]
1960    fn fixed_exceeds_available_clamped() {
1961        let flex = Flex::horizontal().constraints([Constraint::Fixed(60), Constraint::Fixed(60)]);
1962        let rects = flex.split(Rect::new(0, 0, 100, 10));
1963        // First gets 60, second gets remaining 40 (clamped)
1964        assert_eq!(rects[0].width, 60);
1965        assert_eq!(rects[1].width, 40);
1966    }
1967
1968    // --- Percentage that sums beyond 100% ---
1969
1970    #[test]
1971    fn percentage_overflow_clamped() {
1972        let flex = Flex::horizontal()
1973            .constraints([Constraint::Percentage(80.0), Constraint::Percentage(80.0)]);
1974        let rects = flex.split(Rect::new(0, 0, 100, 10));
1975        assert_eq!(rects[0].width, 80);
1976        assert_eq!(rects[1].width, 20); // clamped to remaining
1977    }
1978
1979    // --- Margin reduces available space ---
1980
1981    #[test]
1982    fn margin_reduces_split_area() {
1983        let flex = Flex::horizontal()
1984            .margin(Sides::all(10))
1985            .constraints([Constraint::Fixed(20), Constraint::Min(0)]);
1986        let rects = flex.split(Rect::new(0, 0, 100, 100));
1987        // Inner: 10,10,80,80
1988        assert_eq!(rects[0].x, 10);
1989        assert_eq!(rects[0].y, 10);
1990        assert_eq!(rects[0].width, 20);
1991        assert_eq!(rects[0].height, 80);
1992    }
1993
1994    // --- Builder chain ---
1995
1996    #[test]
1997    fn builder_methods_chain() {
1998        let flex = Flex::vertical()
1999            .direction(Direction::Horizontal)
2000            .gap(3)
2001            .margin(Sides::all(1))
2002            .alignment(Alignment::End)
2003            .constraints([Constraint::Fixed(10)]);
2004        let rects = flex.split(Rect::new(0, 0, 50, 50));
2005        assert_eq!(rects.len(), 1);
2006    }
2007
2008    // --- SpaceBetween with single item ---
2009
2010    #[test]
2011    fn space_between_single_item() {
2012        let flex = Flex::horizontal()
2013            .alignment(Alignment::SpaceBetween)
2014            .constraints([Constraint::Fixed(10)]);
2015        let rects = flex.split(Rect::new(0, 0, 100, 10));
2016        // Single item: starts at 0, no extra spacing
2017        assert_eq!(rects[0].x, 0);
2018        assert_eq!(rects[0].width, 10);
2019    }
2020
2021    #[test]
2022    fn invariant_rects_within_bounds() {
2023        let area = Rect::new(10, 20, 80, 60);
2024        let flex = Flex::horizontal()
2025            .margin(Sides::all(5))
2026            .gap(2)
2027            .constraints([
2028                Constraint::Fixed(15),
2029                Constraint::Percentage(30.0),
2030                Constraint::Min(10),
2031            ]);
2032        let rects = flex.split(area);
2033
2034        // All rects should be within the inner area (after margin)
2035        let inner = area.inner(Sides::all(5));
2036        for rect in &rects {
2037            assert!(
2038                rect.x >= inner.x && rect.right() <= inner.right(),
2039                "Rect {:?} exceeds horizontal bounds of {:?}",
2040                rect,
2041                inner
2042            );
2043            assert!(
2044                rect.y >= inner.y && rect.bottom() <= inner.bottom(),
2045                "Rect {:?} exceeds vertical bounds of {:?}",
2046                rect,
2047                inner
2048            );
2049        }
2050    }
2051
2052    // --- Fill constraint ---
2053
2054    #[test]
2055    fn fill_takes_remaining_space() {
2056        let flex = Flex::horizontal().constraints([Constraint::Fixed(20), Constraint::Fill]);
2057        let rects = flex.split(Rect::new(0, 0, 100, 10));
2058        assert_eq!(rects[0].width, 20);
2059        assert_eq!(rects[1].width, 80); // Fill gets remaining
2060    }
2061
2062    #[test]
2063    fn multiple_fills_share_space() {
2064        let flex = Flex::horizontal().constraints([Constraint::Fill, Constraint::Fill]);
2065        let rects = flex.split(Rect::new(0, 0, 100, 10));
2066        assert_eq!(rects[0].width, 50);
2067        assert_eq!(rects[1].width, 50);
2068    }
2069
2070    // --- FitContent constraint ---
2071
2072    #[test]
2073    fn fit_content_uses_preferred_size() {
2074        let flex = Flex::horizontal().constraints([Constraint::FitContent, Constraint::Fill]);
2075        let rects = flex.split_with_measurer(Rect::new(0, 0, 100, 10), |idx, _| {
2076            if idx == 0 {
2077                LayoutSizeHint {
2078                    min: 5,
2079                    preferred: 30,
2080                    max: None,
2081                }
2082            } else {
2083                LayoutSizeHint::ZERO
2084            }
2085        });
2086        assert_eq!(rects[0].width, 30); // FitContent gets preferred
2087        assert_eq!(rects[1].width, 70); // Fill gets remainder
2088    }
2089
2090    #[test]
2091    fn fit_content_clamps_to_available() {
2092        let flex = Flex::horizontal().constraints([Constraint::FitContent, Constraint::FitContent]);
2093        let rects = flex.split_with_measurer(Rect::new(0, 0, 100, 10), |_, _| LayoutSizeHint {
2094            min: 5,
2095            preferred: 80,
2096            max: None,
2097        });
2098        // First FitContent takes 80, second gets remaining 20
2099        assert_eq!(rects[0].width, 80);
2100        assert_eq!(rects[1].width, 20);
2101    }
2102
2103    #[test]
2104    fn fit_content_without_measurer_gets_zero() {
2105        // Without measurer (via split()), FitContent gets zero from default hint
2106        let flex = Flex::horizontal().constraints([Constraint::FitContent, Constraint::Fill]);
2107        let rects = flex.split(Rect::new(0, 0, 100, 10));
2108        assert_eq!(rects[0].width, 0); // No preferred size
2109        assert_eq!(rects[1].width, 100); // Fill gets all
2110    }
2111
2112    #[test]
2113    fn fit_content_zero_area_returns_empty_rects() {
2114        let flex = Flex::horizontal().constraints([Constraint::FitContent, Constraint::Fill]);
2115        let rects = flex.split_with_measurer(Rect::new(0, 0, 0, 0), |_, _| LayoutSizeHint {
2116            min: 5,
2117            preferred: 10,
2118            max: None,
2119        });
2120        assert_eq!(rects.len(), 2);
2121        assert_eq!(rects[0].width, 0);
2122        assert_eq!(rects[0].height, 0);
2123        assert_eq!(rects[1].width, 0);
2124        assert_eq!(rects[1].height, 0);
2125    }
2126
2127    #[test]
2128    fn fit_content_tiny_available_clamps_to_remaining() {
2129        let flex = Flex::horizontal().constraints([Constraint::FitContent, Constraint::Fill]);
2130        let rects = flex.split_with_measurer(Rect::new(0, 0, 1, 1), |_, _| LayoutSizeHint {
2131            min: 5,
2132            preferred: 10,
2133            max: None,
2134        });
2135        assert_eq!(rects[0].width, 1);
2136        assert_eq!(rects[1].width, 0);
2137    }
2138
2139    // --- FitContentBounded constraint ---
2140
2141    #[test]
2142    fn fit_content_bounded_clamps_to_min() {
2143        let flex = Flex::horizontal().constraints([
2144            Constraint::FitContentBounded { min: 20, max: 50 },
2145            Constraint::Fill,
2146        ]);
2147        let rects = flex.split_with_measurer(Rect::new(0, 0, 100, 10), |_, _| LayoutSizeHint {
2148            min: 5,
2149            preferred: 10, // Below min bound
2150            max: None,
2151        });
2152        assert_eq!(rects[0].width, 20); // Clamped to min bound
2153        assert_eq!(rects[1].width, 80);
2154    }
2155
2156    #[test]
2157    fn fit_content_bounded_respects_small_available() {
2158        let flex = Flex::horizontal().constraints([
2159            Constraint::FitContentBounded { min: 20, max: 50 },
2160            Constraint::Fill,
2161        ]);
2162        let rects = flex.split_with_measurer(Rect::new(0, 0, 5, 2), |_, _| LayoutSizeHint {
2163            min: 5,
2164            preferred: 10,
2165            max: None,
2166        });
2167        // Available is 5 total, so FitContentBounded must clamp to remaining.
2168        assert_eq!(rects[0].width, 5);
2169        assert_eq!(rects[1].width, 0);
2170    }
2171
2172    #[test]
2173    fn fit_content_bounded_clamps_to_max() {
2174        let flex = Flex::horizontal().constraints([
2175            Constraint::FitContentBounded { min: 10, max: 30 },
2176            Constraint::Fill,
2177        ]);
2178        let rects = flex.split_with_measurer(Rect::new(0, 0, 100, 10), |_, _| LayoutSizeHint {
2179            min: 5,
2180            preferred: 50, // Above max bound
2181            max: None,
2182        });
2183        assert_eq!(rects[0].width, 30); // Clamped to max bound
2184        assert_eq!(rects[1].width, 70);
2185    }
2186
2187    #[test]
2188    fn fit_content_bounded_uses_preferred_when_in_range() {
2189        let flex = Flex::horizontal().constraints([
2190            Constraint::FitContentBounded { min: 10, max: 50 },
2191            Constraint::Fill,
2192        ]);
2193        let rects = flex.split_with_measurer(Rect::new(0, 0, 100, 10), |_, _| LayoutSizeHint {
2194            min: 5,
2195            preferred: 35, // Within bounds
2196            max: None,
2197        });
2198        assert_eq!(rects[0].width, 35);
2199        assert_eq!(rects[1].width, 65);
2200    }
2201
2202    // --- FitMin constraint ---
2203
2204    #[test]
2205    fn fit_min_uses_minimum_size() {
2206        let flex = Flex::horizontal().constraints([Constraint::FitMin, Constraint::Fill]);
2207        let rects = flex.split_with_measurer(Rect::new(0, 0, 100, 10), |idx, _| {
2208            if idx == 0 {
2209                LayoutSizeHint {
2210                    min: 15,
2211                    preferred: 40,
2212                    max: None,
2213                }
2214            } else {
2215                LayoutSizeHint::ZERO
2216            }
2217        });
2218        // FitMin gets minimum (15) and DOES NOT grow.
2219        // Fill gets the remaining 85.
2220        assert_eq!(rects[0].width, 15, "FitMin should strict size to min");
2221        assert_eq!(rects[1].width, 85, "Fill should take remaining space");
2222    }
2223
2224    #[test]
2225    fn fit_min_without_measurer_gets_zero() {
2226        let flex = Flex::horizontal().constraints([Constraint::FitMin, Constraint::Fill]);
2227        let rects = flex.split(Rect::new(0, 0, 100, 10));
2228        // Without measurer, min is 0. FitMin gets 0 and does not grow.
2229        // Fill takes all 100.
2230        assert_eq!(rects[0].width, 0);
2231        assert_eq!(rects[1].width, 100);
2232    }
2233
2234    // --- LayoutSizeHint tests ---
2235
2236    #[test]
2237    fn layout_size_hint_zero_is_default() {
2238        assert_eq!(LayoutSizeHint::default(), LayoutSizeHint::ZERO);
2239    }
2240
2241    #[test]
2242    fn layout_size_hint_exact() {
2243        let h = LayoutSizeHint::exact(25);
2244        assert_eq!(h.min, 25);
2245        assert_eq!(h.preferred, 25);
2246        assert_eq!(h.max, Some(25));
2247    }
2248
2249    #[test]
2250    fn layout_size_hint_at_least() {
2251        let h = LayoutSizeHint::at_least(10, 30);
2252        assert_eq!(h.min, 10);
2253        assert_eq!(h.preferred, 30);
2254        assert_eq!(h.max, None);
2255    }
2256
2257    #[test]
2258    fn layout_size_hint_clamp() {
2259        let h = LayoutSizeHint {
2260            min: 10,
2261            preferred: 20,
2262            max: Some(30),
2263        };
2264        assert_eq!(h.clamp(5), 10); // Below min
2265        assert_eq!(h.clamp(15), 15); // In range
2266        assert_eq!(h.clamp(50), 30); // Above max
2267    }
2268
2269    #[test]
2270    fn layout_size_hint_clamp_unbounded() {
2271        let h = LayoutSizeHint::at_least(5, 10);
2272        assert_eq!(h.clamp(3), 5); // Below min
2273        assert_eq!(h.clamp(1000), 1000); // No max, stays as-is
2274    }
2275
2276    #[test]
2277    fn layout_size_hint_clamp_min_greater_than_max() {
2278        // When min > max, min should win (strict lower bound)
2279        let h = LayoutSizeHint {
2280            min: 20,
2281            preferred: 20,
2282            max: Some(10),
2283        };
2284        assert_eq!(h.clamp(5), 20); // 20 > 5, clamped to min
2285        assert_eq!(h.clamp(15), 20); // 20 > 15, clamped to min
2286        assert_eq!(h.clamp(25), 20); // 20 > 10, clamped to min
2287    }
2288
2289    // --- Integration: FitContent with other constraints ---
2290
2291    #[test]
2292    fn fit_content_with_fixed_and_fill() {
2293        let flex = Flex::horizontal().constraints([
2294            Constraint::Fixed(20),
2295            Constraint::FitContent,
2296            Constraint::Fill,
2297        ]);
2298        let rects = flex.split_with_measurer(Rect::new(0, 0, 100, 10), |idx, _| {
2299            if idx == 1 {
2300                LayoutSizeHint {
2301                    min: 5,
2302                    preferred: 25,
2303                    max: None,
2304                }
2305            } else {
2306                LayoutSizeHint::ZERO
2307            }
2308        });
2309        assert_eq!(rects[0].width, 20); // Fixed
2310        assert_eq!(rects[1].width, 25); // FitContent preferred
2311        assert_eq!(rects[2].width, 55); // Fill gets remainder
2312    }
2313
2314    #[test]
2315    fn total_allocation_never_exceeds_available_with_fit_content() {
2316        for available in [10u16, 50, 100, 255] {
2317            let flex = Flex::horizontal().constraints([
2318                Constraint::FitContent,
2319                Constraint::FitContent,
2320                Constraint::Fill,
2321            ]);
2322            let rects =
2323                flex.split_with_measurer(Rect::new(0, 0, available, 10), |_, _| LayoutSizeHint {
2324                    min: 10,
2325                    preferred: 40,
2326                    max: None,
2327                });
2328            let total: u16 = rects.iter().map(|r| r.width).sum();
2329            assert!(
2330                total <= available,
2331                "Total {} exceeded available {} with FitContent",
2332                total,
2333                available
2334            );
2335        }
2336    }
2337
2338    // -----------------------------------------------------------------------
2339    // Stable Layout Rounding Tests (bd-4kq0.4.1)
2340    // -----------------------------------------------------------------------
2341
2342    mod rounding_tests {
2343        use super::super::*;
2344
2345        // --- Sum conservation (REQUIRED) ---
2346
2347        #[test]
2348        fn rounding_conserves_sum_exact() {
2349            let result = round_layout_stable(&[10.0, 20.0, 10.0], 40, None);
2350            assert_eq!(result.iter().copied().sum::<u16>(), 40);
2351            assert_eq!(result.as_slice(), &[10u16, 20u16, 10u16]);
2352        }
2353
2354        #[test]
2355        fn rounding_conserves_sum_fractional() {
2356            let result = round_layout_stable(&[10.4, 20.6, 9.0], 40, None);
2357            assert_eq!(
2358                result.iter().copied().sum::<u16>(),
2359                40,
2360                "Sum must equal total: {:?}",
2361                result
2362            );
2363        }
2364
2365        #[test]
2366        fn rounding_conserves_sum_many_fractions() {
2367            let targets = vec![20.2, 20.2, 20.2, 20.2, 19.2];
2368            let result = round_layout_stable(&targets, 100, None);
2369            assert_eq!(
2370                result.iter().copied().sum::<u16>(),
2371                100,
2372                "Sum must be exactly 100: {:?}",
2373                result
2374            );
2375        }
2376
2377        #[test]
2378        fn rounding_conserves_sum_all_half() {
2379            let targets = vec![10.5, 10.5, 10.5, 10.5];
2380            let result = round_layout_stable(&targets, 42, None);
2381            assert_eq!(
2382                result.iter().copied().sum::<u16>(),
2383                42,
2384                "Sum must be exactly 42: {:?}",
2385                result
2386            );
2387        }
2388
2389        // --- Bounded displacement ---
2390
2391        #[test]
2392        fn rounding_displacement_bounded() {
2393            let targets = vec![33.33, 33.33, 33.34];
2394            let result = round_layout_stable(&targets, 100, None);
2395            assert_eq!(result.iter().copied().sum::<u16>(), 100);
2396
2397            for (i, (&x, &r)) in result.iter().zip(targets.iter()).enumerate() {
2398                let floor = r.floor() as u16;
2399                let ceil = floor + 1;
2400                assert!(
2401                    x == floor || x == ceil,
2402                    "Element {} = {} not in {{floor={}, ceil={}}} of target {}",
2403                    i,
2404                    x,
2405                    floor,
2406                    ceil,
2407                    r
2408                );
2409            }
2410        }
2411
2412        // --- Temporal tie-break (REQUIRED) ---
2413
2414        #[test]
2415        fn temporal_tiebreak_stable_when_unchanged() {
2416            let targets = vec![10.5, 10.5, 10.5, 10.5];
2417            let first = round_layout_stable(&targets, 42, None);
2418            let second = round_layout_stable(&targets, 42, Some(first.clone()));
2419            assert_eq!(
2420                first, second,
2421                "Identical targets should produce identical results"
2422            );
2423        }
2424
2425        #[test]
2426        fn temporal_tiebreak_prefers_previous_direction() {
2427            let targets = vec![10.5, 10.5];
2428            let total = 21;
2429            let first = round_layout_stable(&targets, total, None);
2430            assert_eq!(first.iter().copied().sum::<u16>(), total);
2431            let second = round_layout_stable(&targets, total, Some(first.clone()));
2432            assert_eq!(first, second, "Should maintain rounding direction");
2433        }
2434
2435        #[test]
2436        fn temporal_tiebreak_adapts_to_changed_targets() {
2437            let targets_a = vec![10.5, 10.5];
2438            let result_a = round_layout_stable(&targets_a, 21, None);
2439            let targets_b = vec![15.7, 5.3];
2440            let result_b = round_layout_stable(&targets_b, 21, Some(result_a));
2441            assert_eq!(result_b.iter().copied().sum::<u16>(), 21);
2442            assert!(result_b[0] > result_b[1], "Should follow larger target");
2443        }
2444
2445        // --- Property: min displacement (REQUIRED) ---
2446
2447        #[test]
2448        fn property_min_displacement_brute_force_small() {
2449            let targets = vec![3.3, 3.3, 3.4];
2450            let total: u16 = 10;
2451            let result = round_layout_stable(&targets, total, None);
2452            let our_displacement: f64 = result
2453                .iter()
2454                .zip(targets.iter())
2455                .map(|(&x, &r)| (x as f64 - r).abs())
2456                .sum();
2457
2458            let mut min_displacement = f64::MAX;
2459            let floors: Vec<u16> = targets.iter().map(|&r| r.floor() as u16).collect();
2460            let ceils: Vec<u16> = targets.iter().map(|&r| r.floor() as u16 + 1).collect();
2461
2462            for a in floors[0]..=ceils[0] {
2463                for b in floors[1]..=ceils[1] {
2464                    for c in floors[2]..=ceils[2] {
2465                        if a + b + c == total {
2466                            let disp = (a as f64 - targets[0]).abs()
2467                                + (b as f64 - targets[1]).abs()
2468                                + (c as f64 - targets[2]).abs();
2469                            if disp < min_displacement {
2470                                min_displacement = disp;
2471                            }
2472                        }
2473                    }
2474                }
2475            }
2476
2477            assert!(
2478                (our_displacement - min_displacement).abs() < 1e-10,
2479                "Our displacement {} should match optimal {}: {:?}",
2480                our_displacement,
2481                min_displacement,
2482                result
2483            );
2484        }
2485
2486        // --- Determinism ---
2487
2488        #[test]
2489        fn rounding_deterministic() {
2490            let targets = vec![7.7, 8.3, 14.0];
2491            let a = round_layout_stable(&targets, 30, None);
2492            let b = round_layout_stable(&targets, 30, None);
2493            assert_eq!(a, b, "Same inputs must produce identical outputs");
2494        }
2495
2496        // --- Edge cases ---
2497
2498        #[test]
2499        fn rounding_empty_targets() {
2500            let result = round_layout_stable(&[], 0, None);
2501            assert!(result.is_empty());
2502        }
2503
2504        #[test]
2505        fn rounding_single_element() {
2506            let result = round_layout_stable(&[10.7], 11, None);
2507            assert_eq!(result.as_slice(), &[11u16]);
2508        }
2509
2510        #[test]
2511        fn rounding_zero_total() {
2512            let result = round_layout_stable(&[5.0, 5.0], 0, None);
2513            assert_eq!(result.iter().copied().sum::<u16>(), 0);
2514        }
2515
2516        #[test]
2517        fn rounding_zero_total_with_large_overflow_reaches_zero() {
2518            let result = round_layout_stable(&[65535.0, 65535.0], 0, None);
2519            assert_eq!(result.as_slice(), &[0u16, 0u16]);
2520            assert_eq!(result.iter().copied().sum::<u16>(), 0);
2521        }
2522
2523        #[test]
2524        fn rounding_all_zeros() {
2525            let result = round_layout_stable(&[0.0, 0.0, 0.0], 0, None);
2526            assert_eq!(result.as_slice(), &[0u16, 0u16, 0u16]);
2527        }
2528
2529        #[test]
2530        fn rounding_integer_targets() {
2531            let result = round_layout_stable(&[10.0, 20.0, 30.0], 60, None);
2532            assert_eq!(result.as_slice(), &[10u16, 20u16, 30u16]);
2533        }
2534
2535        #[test]
2536        fn rounding_large_deficit() {
2537            let result = round_layout_stable(&[0.9, 0.9, 0.9], 3, None);
2538            assert_eq!(result.iter().copied().sum::<u16>(), 3);
2539            assert_eq!(result.as_slice(), &[1u16, 1u16, 1u16]);
2540        }
2541
2542        #[test]
2543        fn rounding_with_prev_different_length() {
2544            let result = round_layout_stable(
2545                &[10.5, 10.5],
2546                21,
2547                Some(smallvec::smallvec![11u16, 10u16, 5u16]),
2548            );
2549            assert_eq!(result.iter().copied().sum::<u16>(), 21);
2550        }
2551
2552        #[test]
2553        fn rounding_very_small_fractions() {
2554            let targets = vec![10.001, 20.001, 9.998];
2555            let result = round_layout_stable(&targets, 40, None);
2556            assert_eq!(result.iter().copied().sum::<u16>(), 40);
2557        }
2558
2559        #[test]
2560        fn rounding_conserves_sum_stress() {
2561            let n = 50;
2562            let targets: Vec<f64> = (0..n).map(|i| 2.0 + (i as f64 * 0.037)).collect();
2563            let total = 120u16;
2564            let result = round_layout_stable(&targets, total, None);
2565            assert_eq!(
2566                result.iter().copied().sum::<u16>(),
2567                total,
2568                "Sum must be exactly {} for {} items: {:?}",
2569                total,
2570                n,
2571                result
2572            );
2573        }
2574    }
2575
2576    // -----------------------------------------------------------------------
2577    // Property Tests: Constraint Satisfaction (bd-4kq0.4.3)
2578    // -----------------------------------------------------------------------
2579
2580    mod property_constraint_tests {
2581        use super::super::*;
2582
2583        /// Deterministic LCG pseudo-random number generator (no external deps).
2584        struct Lcg(u64);
2585
2586        impl Lcg {
2587            fn new(seed: u64) -> Self {
2588                Self(seed)
2589            }
2590            fn next_u32(&mut self) -> u32 {
2591                self.0 = self
2592                    .0
2593                    .wrapping_mul(6_364_136_223_846_793_005)
2594                    .wrapping_add(1);
2595                (self.0 >> 33) as u32
2596            }
2597            fn next_u16_range(&mut self, lo: u16, hi: u16) -> u16 {
2598                if lo >= hi {
2599                    return lo;
2600                }
2601                lo + (self.next_u32() % (hi - lo) as u32) as u16
2602            }
2603            fn next_f32(&mut self) -> f32 {
2604                (self.next_u32() & 0x00FF_FFFF) as f32 / 16_777_216.0
2605            }
2606        }
2607
2608        /// Generate a random constraint from the LCG.
2609        fn random_constraint(rng: &mut Lcg) -> Constraint {
2610            match rng.next_u32() % 7 {
2611                0 => Constraint::Fixed(rng.next_u16_range(1, 80)),
2612                1 => Constraint::Percentage(rng.next_f32() * 100.0),
2613                2 => Constraint::Min(rng.next_u16_range(0, 40)),
2614                3 => Constraint::Max(rng.next_u16_range(5, 120)),
2615                4 => {
2616                    let n = rng.next_u32() % 5 + 1;
2617                    let d = rng.next_u32() % 5 + 1;
2618                    Constraint::Ratio(n, d)
2619                }
2620                5 => Constraint::Fill,
2621                _ => Constraint::FitContent,
2622            }
2623        }
2624
2625        #[test]
2626        fn property_constraints_respected_fixed() {
2627            let mut rng = Lcg::new(0xDEAD_BEEF);
2628            for _ in 0..200 {
2629                let fixed_val = rng.next_u16_range(1, 60);
2630                let avail = rng.next_u16_range(10, 200);
2631                let flex = Flex::horizontal().constraints([Constraint::Fixed(fixed_val)]);
2632                let rects = flex.split(Rect::new(0, 0, avail, 10));
2633                assert!(
2634                    rects[0].width <= fixed_val.min(avail),
2635                    "Fixed({}) in avail {} -> width {}",
2636                    fixed_val,
2637                    avail,
2638                    rects[0].width
2639                );
2640            }
2641        }
2642
2643        #[test]
2644        fn property_constraints_respected_max() {
2645            let mut rng = Lcg::new(0xCAFE_BABE);
2646            for _ in 0..200 {
2647                let max_val = rng.next_u16_range(5, 80);
2648                let avail = rng.next_u16_range(10, 200);
2649                let flex =
2650                    Flex::horizontal().constraints([Constraint::Max(max_val), Constraint::Fill]);
2651                let rects = flex.split(Rect::new(0, 0, avail, 10));
2652                assert!(
2653                    rects[0].width <= max_val,
2654                    "Max({}) in avail {} -> width {}",
2655                    max_val,
2656                    avail,
2657                    rects[0].width
2658                );
2659            }
2660        }
2661
2662        #[test]
2663        fn property_constraints_respected_min() {
2664            let mut rng = Lcg::new(0xBAAD_F00D);
2665            for _ in 0..200 {
2666                let min_val = rng.next_u16_range(0, 40);
2667                let avail = rng.next_u16_range(min_val.max(1), 200);
2668                let flex = Flex::horizontal().constraints([Constraint::Min(min_val)]);
2669                let rects = flex.split(Rect::new(0, 0, avail, 10));
2670                assert!(
2671                    rects[0].width >= min_val,
2672                    "Min({}) in avail {} -> width {}",
2673                    min_val,
2674                    avail,
2675                    rects[0].width
2676                );
2677            }
2678        }
2679
2680        #[test]
2681        fn property_constraints_respected_ratio_proportional() {
2682            let mut rng = Lcg::new(0x1234_5678);
2683            for _ in 0..200 {
2684                let n1 = rng.next_u32() % 5 + 1;
2685                let n2 = rng.next_u32() % 5 + 1;
2686                let d = n1 + n2;
2687                let avail = rng.next_u16_range(20, 200);
2688                let flex = Flex::horizontal()
2689                    .constraints([Constraint::Ratio(n1, d), Constraint::Ratio(n2, d)]);
2690                let rects = flex.split(Rect::new(0, 0, avail, 10));
2691                let w1 = rects[0].width as f64;
2692                let w2 = rects[1].width as f64;
2693                let total = w1 + w2;
2694                if total > 0.0 {
2695                    let expected_ratio = n1 as f64 / d as f64;
2696                    let actual_ratio = w1 / total;
2697                    assert!(
2698                        (actual_ratio - expected_ratio).abs() < 0.15 || total < 4.0,
2699                        "Ratio({},{})/({}+{}) avail={}: ~{:.2} got {:.2} (w1={}, w2={})",
2700                        n1,
2701                        d,
2702                        n1,
2703                        n2,
2704                        avail,
2705                        expected_ratio,
2706                        actual_ratio,
2707                        w1,
2708                        w2
2709                    );
2710                }
2711            }
2712        }
2713
2714        #[test]
2715        fn property_total_allocation_never_exceeds_available() {
2716            let mut rng = Lcg::new(0xFACE_FEED);
2717            for _ in 0..500 {
2718                let n = (rng.next_u32() % 6 + 1) as usize;
2719                let constraints: Vec<Constraint> =
2720                    (0..n).map(|_| random_constraint(&mut rng)).collect();
2721                let avail = rng.next_u16_range(5, 200);
2722                let dir = if rng.next_u32().is_multiple_of(2) {
2723                    Direction::Horizontal
2724                } else {
2725                    Direction::Vertical
2726                };
2727                let flex = Flex::default().direction(dir).constraints(constraints);
2728                let area = Rect::new(0, 0, avail, avail);
2729                let rects = flex.split(area);
2730                let total: u16 = rects
2731                    .iter()
2732                    .map(|r| match dir {
2733                        Direction::Horizontal => r.width,
2734                        Direction::Vertical => r.height,
2735                    })
2736                    .sum();
2737                assert!(
2738                    total <= avail,
2739                    "Total {} exceeded available {} with {} constraints",
2740                    total,
2741                    avail,
2742                    n
2743                );
2744            }
2745        }
2746
2747        #[test]
2748        fn property_no_overlap_horizontal() {
2749            let mut rng = Lcg::new(0xABCD_1234);
2750            for _ in 0..300 {
2751                let n = (rng.next_u32() % 5 + 2) as usize;
2752                let constraints: Vec<Constraint> =
2753                    (0..n).map(|_| random_constraint(&mut rng)).collect();
2754                let avail = rng.next_u16_range(20, 200);
2755                let flex = Flex::horizontal().constraints(constraints);
2756                let rects = flex.split(Rect::new(0, 0, avail, 10));
2757
2758                for i in 1..rects.len() {
2759                    let prev_end = rects[i - 1].x + rects[i - 1].width;
2760                    assert!(
2761                        rects[i].x >= prev_end,
2762                        "Overlap at {}: prev ends {}, next starts {}",
2763                        i,
2764                        prev_end,
2765                        rects[i].x
2766                    );
2767                }
2768            }
2769        }
2770
2771        #[test]
2772        fn property_deterministic_across_runs() {
2773            let mut rng = Lcg::new(0x9999_8888);
2774            for _ in 0..100 {
2775                let n = (rng.next_u32() % 5 + 1) as usize;
2776                let constraints: Vec<Constraint> =
2777                    (0..n).map(|_| random_constraint(&mut rng)).collect();
2778                let avail = rng.next_u16_range(10, 200);
2779                let r1 = Flex::horizontal()
2780                    .constraints(constraints.clone())
2781                    .split(Rect::new(0, 0, avail, 10));
2782                let r2 = Flex::horizontal()
2783                    .constraints(constraints)
2784                    .split(Rect::new(0, 0, avail, 10));
2785                assert_eq!(r1, r2, "Determinism violation at avail={}", avail);
2786            }
2787        }
2788    }
2789
2790    // -----------------------------------------------------------------------
2791    // Property Tests: Temporal Stability (bd-4kq0.4.3)
2792    // -----------------------------------------------------------------------
2793
2794    mod property_temporal_tests {
2795        use super::super::*;
2796        use crate::cache::{CoherenceCache, CoherenceId};
2797
2798        /// Deterministic LCG.
2799        struct Lcg(u64);
2800
2801        impl Lcg {
2802            fn new(seed: u64) -> Self {
2803                Self(seed)
2804            }
2805            fn next_u32(&mut self) -> u32 {
2806                self.0 = self
2807                    .0
2808                    .wrapping_mul(6_364_136_223_846_793_005)
2809                    .wrapping_add(1);
2810                (self.0 >> 33) as u32
2811            }
2812        }
2813
2814        #[test]
2815        fn property_temporal_stability_small_resize() {
2816            let constraints = [
2817                Constraint::Percentage(33.3),
2818                Constraint::Percentage(33.3),
2819                Constraint::Fill,
2820            ];
2821            let mut coherence = CoherenceCache::new(64);
2822            let id = CoherenceId::new(&constraints, Direction::Horizontal);
2823
2824            for total in [80u16, 100, 120] {
2825                let flex = Flex::horizontal().constraints(constraints);
2826                let rects = flex.split(Rect::new(0, 0, total, 10));
2827                let widths: Vec<u16> = rects.iter().map(|r| r.width).collect();
2828
2829                let targets: Vec<f64> = widths.iter().map(|&w| w as f64).collect();
2830                let prev = coherence.get(&id);
2831                let rounded = round_layout_stable(&targets, total, prev);
2832
2833                if let Some(old) = coherence.get(&id) {
2834                    let (sum_disp, max_disp) = coherence.displacement(&id, &rounded);
2835                    assert!(
2836                        max_disp <= total.abs_diff(old.iter().copied().sum()) as u32 + 1,
2837                        "max_disp={} too large for size change {} -> {}",
2838                        max_disp,
2839                        old.iter().copied().sum::<u16>(),
2840                        total
2841                    );
2842                    let _ = sum_disp;
2843                }
2844                coherence.store(id, rounded);
2845            }
2846        }
2847
2848        #[test]
2849        fn property_temporal_stability_random_walk() {
2850            let constraints = [
2851                Constraint::Ratio(1, 3),
2852                Constraint::Ratio(1, 3),
2853                Constraint::Ratio(1, 3),
2854            ];
2855            let id = CoherenceId::new(&constraints, Direction::Horizontal);
2856            let mut coherence = CoherenceCache::new(64);
2857            let mut rng = Lcg::new(0x5555_AAAA);
2858            let mut total: u16 = 90;
2859
2860            for step in 0..200 {
2861                let prev_total = total;
2862                let delta = (rng.next_u32() % 7) as i32 - 3;
2863                total = (total as i32 + delta).clamp(10, 250) as u16;
2864
2865                let flex = Flex::horizontal().constraints(constraints);
2866                let rects = flex.split(Rect::new(0, 0, total, 10));
2867                let widths: Vec<u16> = rects.iter().map(|r| r.width).collect();
2868
2869                let targets: Vec<f64> = widths.iter().map(|&w| w as f64).collect();
2870                let prev = coherence.get(&id);
2871                let rounded = round_layout_stable(&targets, total, prev);
2872
2873                if coherence.get(&id).is_some() {
2874                    let (_, max_disp) = coherence.displacement(&id, &rounded);
2875                    let size_change = total.abs_diff(prev_total);
2876                    assert!(
2877                        max_disp <= size_change as u32 + 2,
2878                        "step {}: max_disp={} exceeds size_change={} + 2",
2879                        step,
2880                        max_disp,
2881                        size_change
2882                    );
2883                }
2884                coherence.store(id, rounded);
2885            }
2886        }
2887
2888        #[test]
2889        fn property_temporal_stability_identical_frames() {
2890            let constraints = [
2891                Constraint::Fixed(20),
2892                Constraint::Fill,
2893                Constraint::Fixed(15),
2894            ];
2895            let id = CoherenceId::new(&constraints, Direction::Horizontal);
2896            let mut coherence = CoherenceCache::new(64);
2897
2898            let flex = Flex::horizontal().constraints(constraints);
2899            let rects = flex.split(Rect::new(0, 0, 100, 10));
2900            let widths: Vec<u16> = rects.iter().map(|r| r.width).collect();
2901            coherence.store(id, widths.iter().copied().collect());
2902
2903            for _ in 0..10 {
2904                let targets: Vec<f64> = widths.iter().map(|&w| w as f64).collect();
2905                let prev = coherence.get(&id);
2906                let rounded = round_layout_stable(&targets, 100, prev);
2907                let (sum_disp, _) = coherence.displacement(&id, &rounded);
2908                assert_eq!(sum_disp, 0, "Identical frames: zero displacement");
2909                coherence.store(id, rounded);
2910            }
2911        }
2912
2913        #[test]
2914        fn property_temporal_coherence_sweep() {
2915            let constraints = [
2916                Constraint::Percentage(25.0),
2917                Constraint::Percentage(50.0),
2918                Constraint::Fill,
2919            ];
2920            let id = CoherenceId::new(&constraints, Direction::Horizontal);
2921            let mut coherence = CoherenceCache::new(64);
2922            let mut total_displacement: u64 = 0;
2923
2924            for total in 60u16..=140 {
2925                let flex = Flex::horizontal().constraints(constraints);
2926                let rects = flex.split(Rect::new(0, 0, total, 10));
2927                let widths: Vec<u16> = rects.iter().map(|r| r.width).collect();
2928
2929                let targets: Vec<f64> = widths.iter().map(|&w| w as f64).collect();
2930                let prev = coherence.get(&id);
2931                let rounded = round_layout_stable(&targets, total, prev);
2932
2933                if coherence.get(&id).is_some() {
2934                    let (sum_disp, _) = coherence.displacement(&id, &rounded);
2935                    total_displacement += sum_disp;
2936                }
2937                coherence.store(id, rounded);
2938            }
2939
2940            assert!(
2941                total_displacement <= 80 * 3,
2942                "Total displacement {} exceeds bound for 80-step sweep",
2943                total_displacement
2944            );
2945        }
2946    }
2947
2948    // -----------------------------------------------------------------------
2949    // Snapshot Regression: Canonical Flex/Grid Layouts (bd-4kq0.4.3)
2950    // -----------------------------------------------------------------------
2951
2952    mod snapshot_layout_tests {
2953        use super::super::*;
2954        use crate::grid::{Grid, GridArea};
2955
2956        fn snapshot_flex(
2957            constraints: &[Constraint],
2958            dir: Direction,
2959            width: u16,
2960            height: u16,
2961        ) -> String {
2962            let flex = Flex::default()
2963                .direction(dir)
2964                .constraints(constraints.iter().copied());
2965            let rects = flex.split(Rect::new(0, 0, width, height));
2966            let mut out = format!(
2967                "Flex {:?} {}x{} ({} constraints)\n",
2968                dir,
2969                width,
2970                height,
2971                constraints.len()
2972            );
2973            for (i, r) in rects.iter().enumerate() {
2974                out.push_str(&format!(
2975                    "  [{}] x={} y={} w={} h={}\n",
2976                    i, r.x, r.y, r.width, r.height
2977                ));
2978            }
2979            let total: u16 = rects
2980                .iter()
2981                .map(|r| match dir {
2982                    Direction::Horizontal => r.width,
2983                    Direction::Vertical => r.height,
2984                })
2985                .sum();
2986            out.push_str(&format!("  total={}\n", total));
2987            out
2988        }
2989
2990        fn snapshot_grid(
2991            rows: &[Constraint],
2992            cols: &[Constraint],
2993            areas: &[(&str, GridArea)],
2994            width: u16,
2995            height: u16,
2996        ) -> String {
2997            let mut grid = Grid::new()
2998                .rows(rows.iter().copied())
2999                .columns(cols.iter().copied());
3000            for &(name, area) in areas {
3001                grid = grid.area(name, area);
3002            }
3003            let layout = grid.split(Rect::new(0, 0, width, height));
3004
3005            let mut out = format!(
3006                "Grid {}x{} ({}r x {}c)\n",
3007                width,
3008                height,
3009                rows.len(),
3010                cols.len()
3011            );
3012            for r in 0..rows.len() {
3013                for c in 0..cols.len() {
3014                    let rect = layout.cell(r, c);
3015                    out.push_str(&format!(
3016                        "  [{},{}] x={} y={} w={} h={}\n",
3017                        r, c, rect.x, rect.y, rect.width, rect.height
3018                    ));
3019                }
3020            }
3021            for &(name, _) in areas {
3022                if let Some(rect) = layout.area(name) {
3023                    out.push_str(&format!(
3024                        "  area({}) x={} y={} w={} h={}\n",
3025                        name, rect.x, rect.y, rect.width, rect.height
3026                    ));
3027                }
3028            }
3029            out
3030        }
3031
3032        // --- Flex snapshots: 80x24 ---
3033
3034        #[test]
3035        fn snapshot_flex_thirds_80x24() {
3036            let snap = snapshot_flex(
3037                &[
3038                    Constraint::Ratio(1, 3),
3039                    Constraint::Ratio(1, 3),
3040                    Constraint::Ratio(1, 3),
3041                ],
3042                Direction::Horizontal,
3043                80,
3044                24,
3045            );
3046            assert_eq!(
3047                snap,
3048                "\
3049Flex Horizontal 80x24 (3 constraints)
3050  [0] x=0 y=0 w=26 h=24
3051  [1] x=26 y=0 w=26 h=24
3052  [2] x=52 y=0 w=26 h=24
3053  total=78
3054"
3055            );
3056        }
3057
3058        #[test]
3059        fn snapshot_flex_sidebar_content_80x24() {
3060            let snap = snapshot_flex(
3061                &[Constraint::Fixed(20), Constraint::Fill],
3062                Direction::Horizontal,
3063                80,
3064                24,
3065            );
3066            assert_eq!(
3067                snap,
3068                "\
3069Flex Horizontal 80x24 (2 constraints)
3070  [0] x=0 y=0 w=20 h=24
3071  [1] x=20 y=0 w=60 h=24
3072  total=80
3073"
3074            );
3075        }
3076
3077        #[test]
3078        fn snapshot_flex_header_body_footer_80x24() {
3079            let snap = snapshot_flex(
3080                &[Constraint::Fixed(3), Constraint::Fill, Constraint::Fixed(1)],
3081                Direction::Vertical,
3082                80,
3083                24,
3084            );
3085            assert_eq!(
3086                snap,
3087                "\
3088Flex Vertical 80x24 (3 constraints)
3089  [0] x=0 y=0 w=80 h=3
3090  [1] x=0 y=3 w=80 h=20
3091  [2] x=0 y=23 w=80 h=1
3092  total=24
3093"
3094            );
3095        }
3096
3097        // --- Flex snapshots: 120x40 ---
3098
3099        #[test]
3100        fn snapshot_flex_thirds_120x40() {
3101            let snap = snapshot_flex(
3102                &[
3103                    Constraint::Ratio(1, 3),
3104                    Constraint::Ratio(1, 3),
3105                    Constraint::Ratio(1, 3),
3106                ],
3107                Direction::Horizontal,
3108                120,
3109                40,
3110            );
3111            assert_eq!(
3112                snap,
3113                "\
3114Flex Horizontal 120x40 (3 constraints)
3115  [0] x=0 y=0 w=40 h=40
3116  [1] x=40 y=0 w=40 h=40
3117  [2] x=80 y=0 w=40 h=40
3118  total=120
3119"
3120            );
3121        }
3122
3123        #[test]
3124        fn snapshot_flex_sidebar_content_120x40() {
3125            let snap = snapshot_flex(
3126                &[Constraint::Fixed(20), Constraint::Fill],
3127                Direction::Horizontal,
3128                120,
3129                40,
3130            );
3131            assert_eq!(
3132                snap,
3133                "\
3134Flex Horizontal 120x40 (2 constraints)
3135  [0] x=0 y=0 w=20 h=40
3136  [1] x=20 y=0 w=100 h=40
3137  total=120
3138"
3139            );
3140        }
3141
3142        #[test]
3143        fn snapshot_flex_percentage_mix_120x40() {
3144            let snap = snapshot_flex(
3145                &[
3146                    Constraint::Percentage(25.0),
3147                    Constraint::Percentage(50.0),
3148                    Constraint::Fill,
3149                ],
3150                Direction::Horizontal,
3151                120,
3152                40,
3153            );
3154            assert_eq!(
3155                snap,
3156                "\
3157Flex Horizontal 120x40 (3 constraints)
3158  [0] x=0 y=0 w=30 h=40
3159  [1] x=30 y=0 w=60 h=40
3160  [2] x=90 y=0 w=30 h=40
3161  total=120
3162"
3163            );
3164        }
3165
3166        // --- Grid snapshots: 80x24 ---
3167
3168        #[test]
3169        fn snapshot_grid_2x2_80x24() {
3170            let snap = snapshot_grid(
3171                &[Constraint::Fixed(3), Constraint::Fill],
3172                &[Constraint::Fixed(20), Constraint::Fill],
3173                &[
3174                    ("header", GridArea::span(0, 0, 1, 2)),
3175                    ("sidebar", GridArea::span(1, 0, 1, 1)),
3176                    ("content", GridArea::cell(1, 1)),
3177                ],
3178                80,
3179                24,
3180            );
3181            assert_eq!(
3182                snap,
3183                "\
3184Grid 80x24 (2r x 2c)
3185  [0,0] x=0 y=0 w=20 h=3
3186  [0,1] x=20 y=0 w=60 h=3
3187  [1,0] x=0 y=3 w=20 h=21
3188  [1,1] x=20 y=3 w=60 h=21
3189  area(header) x=0 y=0 w=80 h=3
3190  area(sidebar) x=0 y=3 w=20 h=21
3191  area(content) x=20 y=3 w=60 h=21
3192"
3193            );
3194        }
3195
3196        #[test]
3197        fn snapshot_grid_3x3_80x24() {
3198            let snap = snapshot_grid(
3199                &[Constraint::Fixed(1), Constraint::Fill, Constraint::Fixed(1)],
3200                &[
3201                    Constraint::Fixed(10),
3202                    Constraint::Fill,
3203                    Constraint::Fixed(10),
3204                ],
3205                &[],
3206                80,
3207                24,
3208            );
3209            assert_eq!(
3210                snap,
3211                "\
3212Grid 80x24 (3r x 3c)
3213  [0,0] x=0 y=0 w=10 h=1
3214  [0,1] x=10 y=0 w=60 h=1
3215  [0,2] x=70 y=0 w=10 h=1
3216  [1,0] x=0 y=1 w=10 h=22
3217  [1,1] x=10 y=1 w=60 h=22
3218  [1,2] x=70 y=1 w=10 h=22
3219  [2,0] x=0 y=23 w=10 h=1
3220  [2,1] x=10 y=23 w=60 h=1
3221  [2,2] x=70 y=23 w=10 h=1
3222"
3223            );
3224        }
3225
3226        // --- Grid snapshots: 120x40 ---
3227
3228        #[test]
3229        fn snapshot_grid_2x2_120x40() {
3230            let snap = snapshot_grid(
3231                &[Constraint::Fixed(3), Constraint::Fill],
3232                &[Constraint::Fixed(20), Constraint::Fill],
3233                &[
3234                    ("header", GridArea::span(0, 0, 1, 2)),
3235                    ("sidebar", GridArea::span(1, 0, 1, 1)),
3236                    ("content", GridArea::cell(1, 1)),
3237                ],
3238                120,
3239                40,
3240            );
3241            assert_eq!(
3242                snap,
3243                "\
3244Grid 120x40 (2r x 2c)
3245  [0,0] x=0 y=0 w=20 h=3
3246  [0,1] x=20 y=0 w=100 h=3
3247  [1,0] x=0 y=3 w=20 h=37
3248  [1,1] x=20 y=3 w=100 h=37
3249  area(header) x=0 y=0 w=120 h=3
3250  area(sidebar) x=0 y=3 w=20 h=37
3251  area(content) x=20 y=3 w=100 h=37
3252"
3253            );
3254        }
3255
3256        #[test]
3257        fn snapshot_grid_dashboard_120x40() {
3258            let snap = snapshot_grid(
3259                &[
3260                    Constraint::Fixed(3),
3261                    Constraint::Percentage(60.0),
3262                    Constraint::Fill,
3263                ],
3264                &[Constraint::Percentage(30.0), Constraint::Fill],
3265                &[
3266                    ("nav", GridArea::span(0, 0, 1, 2)),
3267                    ("chart", GridArea::cell(1, 0)),
3268                    ("detail", GridArea::cell(1, 1)),
3269                    ("log", GridArea::span(2, 0, 1, 2)),
3270                ],
3271                120,
3272                40,
3273            );
3274            assert_eq!(
3275                snap,
3276                "\
3277Grid 120x40 (3r x 2c)
3278  [0,0] x=0 y=0 w=36 h=3
3279  [0,1] x=36 y=0 w=84 h=3
3280  [1,0] x=0 y=3 w=36 h=24
3281  [1,1] x=36 y=3 w=84 h=24
3282  [2,0] x=0 y=27 w=36 h=13
3283  [2,1] x=36 y=27 w=84 h=13
3284  area(nav) x=0 y=0 w=120 h=3
3285  area(chart) x=0 y=3 w=36 h=24
3286  area(detail) x=36 y=3 w=84 h=24
3287  area(log) x=0 y=27 w=120 h=13
3288"
3289            );
3290        }
3291    }
3292
3293    mod arena_flex_proptests {
3294        use super::*;
3295        use proptest::prelude::*;
3296
3297        fn arb_constraint() -> impl Strategy<Value = Constraint> {
3298            prop_oneof![
3299                (0u16..=60).prop_map(Constraint::Fixed),
3300                (0u16..=100).prop_map(|p| Constraint::Percentage(f32::from(p))),
3301                (0u16..=60).prop_map(Constraint::Min),
3302                (1u16..=60).prop_map(Constraint::Max),
3303                (0u32..=10, 1u32..=10).prop_map(|(n, d)| Constraint::Ratio(n, d)),
3304                Just(Constraint::Fill),
3305                Just(Constraint::FitContent),
3306                Just(Constraint::FitMin),
3307            ]
3308        }
3309
3310        fn arb_alignment() -> impl Strategy<Value = Alignment> {
3311            prop_oneof![
3312                Just(Alignment::Start),
3313                Just(Alignment::Center),
3314                Just(Alignment::End),
3315                Just(Alignment::SpaceBetween),
3316                Just(Alignment::SpaceAround),
3317            ]
3318        }
3319
3320        proptest! {
3321            #![proptest_config(ProptestConfig::with_cases(512))]
3322
3323            #[test]
3324            fn flex_split_in_equals_split(
3325                horiz in any::<bool>(),
3326                rtl in any::<bool>(),
3327                gap in 0u16..=4,
3328                w in 0u16..=200,
3329                h in 0u16..=80,
3330                alignment in arb_alignment(),
3331                constraints in prop::collection::vec(arb_constraint(), 0..=20),
3332            ) {
3333                let mut arena = ftui_core::arena::FrameArena::new(16 * 1024);
3334                let flex = if horiz { Flex::horizontal() } else { Flex::vertical() }
3335                    .gap(gap)
3336                    .alignment(alignment)
3337                    .flow_direction(if rtl {
3338                        direction::FlowDirection::Rtl
3339                    } else {
3340                        direction::FlowDirection::Ltr
3341                    })
3342                    .constraints(constraints);
3343
3344                let area = Rect::new(2, 3, w, h);
3345                let owned = flex.split(area);
3346                let in_arena = flex.split_in(&arena, area);
3347                prop_assert_eq!(in_arena, owned.as_slice());
3348
3349                arena.reset();
3350                let measurer = |idx: usize, avail: u16| LayoutSizeHint {
3351                    min: ((idx as u16) * 2).min(avail),
3352                    preferred: ((idx as u16) * 5 + 3).min(avail),
3353                    max: Some(40),
3354                };
3355                let owned_m = flex.split_with_measurer(area, measurer);
3356                let in_arena_m = flex.split_with_measurer_in(&arena, area, measurer);
3357                prop_assert_eq!(in_arena_m, owned_m.as_slice());
3358            }
3359        }
3360    }
3361}