ftui-layout 0.4.0

Flex and grid layout solvers for FrankenTUI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
#![forbid(unsafe_code)]

//! Responsive layout switching: different [`Flex`] configurations per breakpoint.
//!
//! [`ResponsiveLayout`] maps [`Breakpoint`] tiers to [`Flex`] layouts. When
//! splitting an area, it auto-detects the current breakpoint from the area
//! width and resolves the appropriate layout using [`Responsive`] inheritance.
//!
//! # Usage
//!
//! ```ignore
//! use ftui_layout::{Flex, Constraint, Breakpoint, Breakpoints, ResponsiveLayout};
//!
//! // Mobile: single column. Desktop: sidebar + content.
//! let layout = ResponsiveLayout::new(
//!         Flex::vertical()
//!             .constraints([Constraint::Fill, Constraint::Fill]),
//!     )
//!     .at(Breakpoint::Md,
//!         Flex::horizontal()
//!             .constraints([Constraint::Fixed(30), Constraint::Fill]),
//!     );
//!
//! let area = ftui_core::geometry::Rect::new(0, 0, 120, 40);
//! let result = layout.split(area);
//! assert_eq!(result.breakpoint, Breakpoint::Lg);
//! assert_eq!(result.rects.len(), 2);
//! ```
//!
//! # Invariants
//!
//! 1. The base layout (`Xs`) always has a value (enforced by constructor).
//! 2. Breakpoint resolution inherits from smaller tiers (via [`Responsive`]).
//! 3. `split()` auto-detects breakpoint from area width.
//! 4. `split_for()` uses an explicit breakpoint (no auto-detection).
//! 5. Result count may differ between breakpoints (caller must handle this).
//!
//! # Failure Modes
//!
//! - Empty area: delegates to [`Flex::split`] (returns zero-sized rects).
//! - Breakpoint changes mid-session: caller must handle state transitions
//!   (e.g., re-mapping children). Use [`ResponsiveSplit::breakpoint`] to
//!   detect changes.

use super::{Breakpoint, Breakpoints, Flex, Rect, Responsive};

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

/// Result of a responsive layout split.
#[derive(Debug, Clone, PartialEq)]
pub struct ResponsiveSplit {
    /// The breakpoint that was active for this split.
    pub breakpoint: Breakpoint,
    /// The resulting layout rectangles.
    pub rects: crate::Rects,
}

/// A breakpoint-aware layout that switches [`Flex`] configuration at different
/// terminal widths.
///
/// Wraps [`Responsive<Flex>`] with auto-detection of breakpoints from area
/// width. Each breakpoint tier can define a completely different layout
/// (direction, constraints, gaps, margins).
#[derive(Debug, Clone)]
pub struct ResponsiveLayout {
    /// Per-breakpoint Flex configurations.
    layouts: Responsive<Flex>,
    /// Breakpoint thresholds for width classification.
    breakpoints: Breakpoints,
}

// ---------------------------------------------------------------------------
// Construction
// ---------------------------------------------------------------------------

impl ResponsiveLayout {
    /// Create a responsive layout with a base layout for `Xs`.
    ///
    /// All larger breakpoints inherit this layout until explicitly overridden.
    #[must_use]
    pub fn new(base: Flex) -> Self {
        Self {
            layouts: Responsive::new(base),
            breakpoints: Breakpoints::DEFAULT,
        }
    }

    /// Set the layout for a specific breakpoint (builder pattern).
    #[must_use]
    pub fn at(mut self, bp: Breakpoint, layout: Flex) -> Self {
        self.layouts.set(bp, layout);
        self
    }

    /// Override the breakpoint thresholds (builder pattern).
    ///
    /// Defaults to [`Breakpoints::DEFAULT`] (60/90/120/160).
    #[must_use]
    pub fn with_breakpoints(mut self, breakpoints: Breakpoints) -> Self {
        self.breakpoints = breakpoints;
        self
    }

    /// Set the layout for a specific breakpoint (mutating).
    pub fn set(&mut self, bp: Breakpoint, layout: Flex) {
        self.layouts.set(bp, layout);
    }

    /// Clear the override for a specific breakpoint, reverting to inheritance.
    ///
    /// Clearing `Xs` is a no-op.
    pub fn clear(&mut self, bp: Breakpoint) {
        self.layouts.clear(bp);
    }
}

// ---------------------------------------------------------------------------
// Splitting
// ---------------------------------------------------------------------------

impl ResponsiveLayout {
    /// Split the area using auto-detected breakpoint from width.
    ///
    /// Classifies `area.width` into a [`Breakpoint`], resolves the
    /// corresponding [`Flex`], and splits the area.
    #[must_use]
    pub fn split(&self, area: Rect) -> ResponsiveSplit {
        let bp = self.breakpoints.classify_width(area.width);
        self.split_for(bp, area)
    }

    /// Split the area using an explicit breakpoint.
    ///
    /// Use this when you already know the active breakpoint (e.g., from
    /// a shared app-level breakpoint state).
    #[must_use]
    pub fn split_for(&self, bp: Breakpoint, area: Rect) -> ResponsiveSplit {
        let flex = self.layouts.resolve(bp);
        ResponsiveSplit {
            breakpoint: bp,
            rects: flex.split(area),
        }
    }

    /// Get the active breakpoint for a given width.
    #[must_use]
    pub fn classify(&self, width: u16) -> Breakpoint {
        self.breakpoints.classify_width(width)
    }

    /// Get the Flex configuration for a given breakpoint.
    #[must_use]
    pub fn layout_for(&self, bp: Breakpoint) -> &Flex {
        self.layouts.resolve(bp)
    }

    /// Whether a specific breakpoint has an explicit (non-inherited) layout.
    #[must_use]
    pub fn has_explicit(&self, bp: Breakpoint) -> bool {
        self.layouts.has_explicit(bp)
    }

    /// Get the breakpoint thresholds.
    #[must_use]
    pub fn breakpoints(&self) -> Breakpoints {
        self.breakpoints
    }

    /// Number of rects that would be produced for a given breakpoint.
    ///
    /// Useful for pre-allocating or checking layout changes without
    /// performing the full split.
    #[must_use]
    pub fn constraint_count(&self, bp: Breakpoint) -> usize {
        self.layouts.resolve(bp).constraint_count()
    }

    /// Check if a width change would cause a breakpoint transition.
    ///
    /// Returns `Some((old, new))` if the breakpoint changed, `None` otherwise.
    #[must_use]
    pub fn detect_transition(
        &self,
        old_width: u16,
        new_width: u16,
    ) -> Option<(Breakpoint, Breakpoint)> {
        let old_bp = self.breakpoints.classify_width(old_width);
        let new_bp = self.breakpoints.classify_width(new_width);
        if old_bp != new_bp {
            Some((old_bp, new_bp))
        } else {
            None
        }
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    fn single_column() -> Flex {
        Flex::vertical().constraints([Constraint::Fill])
    }

    fn two_column() -> Flex {
        Flex::horizontal().constraints([Constraint::Fixed(30), Constraint::Fill])
    }

    fn three_column() -> Flex {
        Flex::horizontal().constraints([
            Constraint::Fixed(25),
            Constraint::Fill,
            Constraint::Fixed(25),
        ])
    }

    fn area(w: u16, h: u16) -> Rect {
        Rect::new(0, 0, w, h)
    }

    #[test]
    fn base_layout_at_all_breakpoints() {
        let layout = ResponsiveLayout::new(single_column());
        for bp in Breakpoint::ALL {
            let result = layout.split_for(bp, area(80, 24));
            assert_eq!(result.rects.len(), 1);
        }
    }

    #[test]
    fn switches_at_breakpoint() {
        let layout = ResponsiveLayout::new(single_column()).at(Breakpoint::Md, two_column());

        // Xs (width < 60): single column
        let result = layout.split(area(50, 24));
        assert_eq!(result.breakpoint, Breakpoint::Xs);
        assert_eq!(result.rects.len(), 1);

        // Md (width 90-119): two columns
        let result = layout.split(area(100, 24));
        assert_eq!(result.breakpoint, Breakpoint::Md);
        assert_eq!(result.rects.len(), 2);
    }

    #[test]
    fn inherits_from_smaller() {
        let layout = ResponsiveLayout::new(single_column()).at(Breakpoint::Md, two_column());

        // Lg inherits from Md
        let result = layout.split(area(130, 24));
        assert_eq!(result.breakpoint, Breakpoint::Lg);
        assert_eq!(result.rects.len(), 2);
    }

    #[test]
    fn three_tier_layout() {
        let layout = ResponsiveLayout::new(single_column())
            .at(Breakpoint::Sm, two_column())
            .at(Breakpoint::Lg, three_column());

        assert_eq!(layout.split(area(40, 24)).rects.len(), 1); // Xs
        assert_eq!(layout.split(area(70, 24)).rects.len(), 2); // Sm
        assert_eq!(layout.split(area(100, 24)).rects.len(), 2); // Md inherits Sm
        assert_eq!(layout.split(area(130, 24)).rects.len(), 3); // Lg
        assert_eq!(layout.split(area(170, 24)).rects.len(), 3); // Xl inherits Lg
    }

    #[test]
    fn split_for_ignores_width() {
        let layout = ResponsiveLayout::new(single_column()).at(Breakpoint::Lg, two_column());

        // Even though area is narrow, split_for uses the explicit breakpoint.
        let result = layout.split_for(Breakpoint::Lg, area(40, 24));
        assert_eq!(result.breakpoint, Breakpoint::Lg);
        assert_eq!(result.rects.len(), 2);
    }

    #[test]
    fn custom_breakpoints() {
        let layout = ResponsiveLayout::new(single_column())
            .at(Breakpoint::Sm, two_column())
            .with_breakpoints(Breakpoints::new(40, 80, 120));

        // Width 50 ≥ 40 → Sm (custom threshold)
        let result = layout.split(area(50, 24));
        assert_eq!(result.breakpoint, Breakpoint::Sm);
        assert_eq!(result.rects.len(), 2);
    }

    #[test]
    fn detect_transition_some() {
        let layout = ResponsiveLayout::new(single_column());

        // 50→100 crosses from Xs to Md (default breakpoints: sm=60, md=90)
        let transition = layout.detect_transition(50, 100);
        assert!(transition.is_some());
        let (old, new) = transition.unwrap();
        assert_eq!(old, Breakpoint::Xs);
        assert_eq!(new, Breakpoint::Md);
    }

    #[test]
    fn detect_transition_none() {
        let layout = ResponsiveLayout::new(single_column());

        // 70→80 stays within Sm
        assert!(layout.detect_transition(70, 80).is_none());
    }

    #[test]
    fn classify_width() {
        let layout = ResponsiveLayout::new(single_column());
        assert_eq!(layout.classify(40), Breakpoint::Xs);
        assert_eq!(layout.classify(60), Breakpoint::Sm);
        assert_eq!(layout.classify(90), Breakpoint::Md);
        assert_eq!(layout.classify(120), Breakpoint::Lg);
        assert_eq!(layout.classify(160), Breakpoint::Xl);
    }

    #[test]
    fn constraint_count() {
        let layout = ResponsiveLayout::new(single_column())
            .at(Breakpoint::Md, two_column())
            .at(Breakpoint::Lg, three_column());

        assert_eq!(layout.constraint_count(Breakpoint::Xs), 1);
        assert_eq!(layout.constraint_count(Breakpoint::Sm), 1); // Inherits Xs
        assert_eq!(layout.constraint_count(Breakpoint::Md), 2);
        assert_eq!(layout.constraint_count(Breakpoint::Lg), 3);
    }

    #[test]
    fn layout_for_access() {
        let layout = ResponsiveLayout::new(single_column()).at(Breakpoint::Md, two_column());

        let flex = layout.layout_for(Breakpoint::Md);
        assert_eq!(flex.constraint_count(), 2);
    }

    #[test]
    fn has_explicit_check() {
        let layout = ResponsiveLayout::new(single_column()).at(Breakpoint::Lg, two_column());

        assert!(layout.has_explicit(Breakpoint::Xs));
        assert!(!layout.has_explicit(Breakpoint::Sm));
        assert!(!layout.has_explicit(Breakpoint::Md));
        assert!(layout.has_explicit(Breakpoint::Lg));
    }

    #[test]
    fn set_mutating() {
        let mut layout = ResponsiveLayout::new(single_column());
        layout.set(Breakpoint::Xl, three_column());
        assert_eq!(layout.constraint_count(Breakpoint::Xl), 3);
    }

    #[test]
    fn clear_reverts_to_inheritance() {
        let mut layout = ResponsiveLayout::new(single_column()).at(Breakpoint::Md, two_column());

        assert_eq!(layout.constraint_count(Breakpoint::Md), 2);
        layout.clear(Breakpoint::Md);
        assert_eq!(layout.constraint_count(Breakpoint::Md), 1); // Inherits Xs
    }

    #[test]
    fn empty_area_returns_zero_rects() {
        let layout = ResponsiveLayout::new(two_column());
        let result = layout.split(area(0, 0));
        assert_eq!(result.breakpoint, Breakpoint::Xs);
        // Flex::split returns default rects for empty area
        assert_eq!(result.rects.len(), 2);
        assert!(result.rects.iter().all(|r| r.width == 0 && r.height == 0));
    }

    #[test]
    fn rect_dimensions_correct() {
        let layout = ResponsiveLayout::new(
            Flex::horizontal().constraints([Constraint::Fixed(20), Constraint::Fill]),
        );

        let result = layout.split(area(100, 30));
        assert_eq!(result.rects[0].width, 20);
        assert_eq!(result.rects[0].height, 30);
        assert_eq!(result.rects[1].width, 80);
        assert_eq!(result.rects[1].height, 30);
    }

    #[test]
    fn breakpoints_accessor() {
        let bps = Breakpoints::new(50, 80, 110);
        let layout = ResponsiveLayout::new(single_column()).with_breakpoints(bps);
        assert_eq!(layout.breakpoints(), bps);
    }

    #[test]
    fn responsive_split_debug() {
        let split = ResponsiveSplit {
            breakpoint: Breakpoint::Md,
            rects: smallvec::smallvec![Rect::new(0, 0, 50, 24)],
        };
        let dbg = format!("{:?}", split);
        assert!(dbg.contains("Md"));
    }
}