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