minui 0.3.0

A minimalist Rust framework for TUIs and terminal games.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
//! # Container Widget
//!
//! A powerful layout management widget that automatically arranges and positions child
//! widgets within structured containers. The container system forms the backbone of
//! MinUI's layout capabilities, providing flexible arrangements with automatic sizing,
//! borders, padding, and alignment options.
//!
//! ## Features
//!
//! - **Automatic layout**: Intelligent child widget positioning and sizing
//! - **Dual layout modes**: Vertical stacking and horizontal arrangement
//! - **Flexible borders**: Optional visible borders with customizable styles
//! - **Advanced padding**: Per-side padding control with uniform options
//! - **Auto-sizing**: Containers adapt to content or fixed dimensions
//! - **Content alignment**: Normal positioning or automatic centering
//! - **Nested containers**: Support for complex hierarchical layouts
//!
//! ## Layout System
//!
//! Containers use a CSS Flexbox-inspired layout model:
//!
//! ```text
//! Vertical Layout:           Horizontal Layout:
//! ┌─────────────────┐       ┌─────┬─────┬─────┐
//! │    Widget 1     │       │ W1  │ W2  │ W3  │
//! ├─────────────────┤       │     │     │     │
//! │    Widget 2     │       │     │     │     │
//! ├─────────────────┤       └─────┴─────┴─────┘
//! │    Widget 3     │
//! └─────────────────┘
//! ```
//!
//! ## Basic Usage
//!
//! ```rust
//! use minui::{Container, Label, Text, LayoutDirection};
//!
//! // Create a vertical layout
//! let vertical_container = Container::vertical()
//!     .add_child(Label::new("Title"))
//!     .add_child(Text::new("Content goes here"))
//!     .add_child(Text::new("More content"));
//!
//! // Create a horizontal layout
//! let horizontal_container = Container::horizontal()
//!     .add_child(Text::new("Left"))
//!     .add_child(Text::new("Center"))
//!     .add_child(Text::new("Right"));
//! ```
//!
//! ## Styled Containers
//!
//! ```rust
//! use minui::{Container, BorderChars, Color, ColorPair, Padding};
//!
//! let styled_container = Container::new(LayoutDirection::Vertical)
//!     .with_border(BorderChars::double_line())
//!     .with_border_color(Some(ColorPair::new(Color::Blue, Color::Black)))
//!     .with_background_color(Some(ColorPair::new(Color::White, Color::Gray)))
//!     .with_padding(Padding::uniform(2))
//!     .with_content_alignment(ContentAlignment::AutoCenter);
//! ```
//!
//! ## Advanced Layouts
//!
//! ```rust
//! use minui::{Container, Panel, TextBlock, LayoutDirection, Padding};
//!
//! // Create a complex dashboard layout
//! let dashboard = Container::vertical()
//!     .with_padding(Padding::uniform(1))
//!     .add_child(
//!         Panel::new(60, 3)
//!             .with_header("System Dashboard")
//!             .with_body("Welcome to the monitoring interface")
//!     )
//!     .add_child(
//!         Container::horizontal()
//!             .add_child(
//!                 Panel::new(30, 10)
//!                     .with_header("CPU Usage")
//!                     .with_body("45% utilization")
//!             )
//!             .add_child(
//!                 Panel::new(30, 10)
//!                     .with_header("Memory")
//!                     .with_body("2.1GB / 8GB used")
//!             )
//!     );
//! ```
//!
//! ## Responsive Design
//!
//! ```rust
//! use minui::{Container, Text, LayoutDirection, ContentAlignment};
//!
//! // Container that adapts to available space
//! let responsive_layout = Container::new(LayoutDirection::Vertical)
//!     .with_auto_size(true)
//!     .with_content_alignment(ContentAlignment::AutoCenter)
//!     .add_child(Text::new("This content will be centered"))
//!     .add_child(Text::new("And this container will size to fit"));
//! ```
//!
//! Container widgets form the foundation of MinUI's layout system, enabling the creation
//! of sophisticated terminal user interfaces with minimal code and maximum flexibility.

use super::{BorderChars, Widget};
use crate::widgets::common::WindowView;
use crate::{Color, ColorPair, Result, Window};

/// Layout direction for container children
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum LayoutDirection {
    /// Stack children vertically (like CSS flex-direction: column)
    Vertical,
    /// Arrange children horizontally (like CSS flex-direction: row)
    Horizontal,
}

/// Border visibility and styling options
#[derive(Debug, Clone)]
pub enum BorderStyle {
    /// No border - invisible container
    None,
    /// Visible border with specified character set
    Visible(BorderChars),
}

/// Padding configuration for containers
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Padding {
    pub top: u16,
    pub right: u16,
    pub bottom: u16,
    pub left: u16,
}

/// Content alignment within a container
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ContentAlignment {
    /// Content positioned normally within the container
    Normal,
    /// Content automatically centered within the container's full width
    AutoCenter,
}

impl Padding {
    /// Create uniform padding on all sides
    pub fn uniform(amount: u16) -> Self {
        Self {
            top: amount,
            right: amount,
            bottom: amount,
            left: amount,
        }
    }

    /// Create asymmetric padding (vertical, horizontal)
    pub fn symmetric(vertical: u16, horizontal: u16) -> Self {
        Self {
            top: vertical,
            right: horizontal,
            bottom: vertical,
            left: horizontal,
        }
    }

    /// Create completely custom padding
    pub fn custom(top: u16, right: u16, bottom: u16, left: u16) -> Self {
        Self {
            top,
            right,
            bottom,
            left,
        }
    }

    /// Total horizontal padding (left + right)
    pub fn horizontal_total(&self) -> u16 {
        self.left + self.right
    }

    /// Total vertical padding (top + bottom)
    pub fn vertical_total(&self) -> u16 {
        self.top + self.bottom
    }
}

impl Default for Padding {
    fn default() -> Self {
        Self::uniform(0)
    }
}

/// A layout-managed container widget that can hold multiple child widgets
pub struct Container {
    /// X-coordinate of the container position
    x: u16,
    /// Y-coordinate of the container position
    y: u16,
    /// Width of the container (including borders)
    width: u16,
    /// Height of the container (including borders)
    height: u16,
    /// Border styling
    border_style: BorderStyle,
    /// Optional border color
    border_color: Option<ColorPair>,
    /// Child widgets managed by this container
    children: Vec<Box<dyn Widget>>,
    /// Layout direction for children
    layout_direction: LayoutDirection,
    /// Internal padding
    padding: Padding,
    /// Spacing between child widgets
    child_spacing: u16,
    /// Whether to automatically size based on content
    auto_size: bool,
    /// Whether to take up full terminal window size
    fullscreen: bool,
    /// Content alignment within the container
    content_alignment: ContentAlignment,
}

impl Container {
    /// Creates a new container at the specified position
    ///
    /// # Arguments
    /// * `x` - X-coordinate position
    /// * `y` - Y-coordinate position
    /// * `width` - Container width (0 for auto-sizing)
    /// * `height` - Container height (0 for auto-sizing)
    pub fn new(x: u16, y: u16, width: u16, height: u16) -> Self {
        Self {
            x,
            y,
            width,
            height,
            border_style: BorderStyle::Visible(BorderChars::single_line()),
            border_color: None,
            children: Vec::new(),
            layout_direction: LayoutDirection::Vertical,
            padding: Padding::uniform(1),
            child_spacing: 0,
            auto_size: width == 0 || height == 0,
            fullscreen: false,
            content_alignment: ContentAlignment::Normal,
        }
    }

    /// Creates a fullscreen container that takes up the entire terminal
    pub fn fullscreen() -> Self {
        Self {
            x: 0,
            y: 0,
            width: 0, // Will be set by update_fullscreen_size
            height: 0,
            border_style: BorderStyle::None,
            border_color: None,
            children: Vec::new(),
            layout_direction: LayoutDirection::Vertical,
            padding: Padding::uniform(0),
            child_spacing: 0,
            auto_size: false,
            fullscreen: true,
            content_alignment: ContentAlignment::Normal,
        }
    }

    /// Creates a fullscreen container with the given terminal dimensions
    pub fn fullscreen_with_size(width: u16, height: u16) -> Self {
        let mut container = Self::fullscreen();
        container.update_fullscreen_size(width, height);
        container
    }

    /// Creates a vertical layout container (VBox equivalent)
    pub fn vertical() -> Self {
        Self::new(0, 0, 0, 0).with_layout_direction(LayoutDirection::Vertical)
    }

    /// Creates a horizontal layout container (HBox equivalent)
    pub fn horizontal() -> Self {
        Self::new(0, 0, 0, 0).with_layout_direction(LayoutDirection::Horizontal)
    }

    /// Sets the border style for the container
    pub fn with_border_style(mut self, style: BorderStyle) -> Self {
        self.border_style = style;
        self
    }

    /// Sets visible border with specified character set
    pub fn with_border(mut self, chars: BorderChars) -> Self {
        self.border_style = BorderStyle::Visible(chars);
        self
    }

    /// Removes the border (invisible container)
    pub fn without_border(mut self) -> Self {
        self.border_style = BorderStyle::None;
        self
    }

    /// Sets the border color
    pub fn with_border_color(mut self, color: Color) -> Self {
        self.border_color = Some(ColorPair::new(color, Color::Transparent));
        self
    }

    /// Sets the layout direction for children
    pub fn with_layout_direction(mut self, direction: LayoutDirection) -> Self {
        self.layout_direction = direction;
        self
    }

    /// Sets uniform padding on all sides
    pub fn with_padding(mut self, padding: u16) -> Self {
        self.padding = Padding::uniform(padding);
        if self.auto_size {
            self.calculate_size();
        }
        self
    }

    /// Sets custom padding configuration
    pub fn with_padding_config(mut self, padding: Padding) -> Self {
        self.padding = padding;
        if self.auto_size {
            self.calculate_size();
        }
        self
    }

    /// Sets content to auto-center within the container
    pub fn with_auto_center(mut self) -> Self {
        self.content_alignment = ContentAlignment::AutoCenter;
        self
    }

    /// Sets spacing between child widgets
    pub fn with_child_spacing(mut self, spacing: u16) -> Self {
        self.child_spacing = spacing;
        if self.auto_size {
            self.calculate_size();
        }
        self
    }

    /// Enables or disables automatic sizing
    pub fn with_auto_size(mut self, auto_size: bool) -> Self {
        self.auto_size = auto_size;
        if auto_size {
            self.calculate_size();
        }
        self
    }

    /// Adds a child widget to the container
    pub fn add_child(mut self, widget: impl Widget + 'static) -> Self {
        self.children.push(Box::new(widget));
        if self.auto_size {
            self.calculate_size();
        }
        self
    }

    /// Adds multiple child widgets at once
    pub fn add_children(mut self, widgets: Vec<Box<dyn Widget>>) -> Self {
        self.children.extend(widgets);
        if self.auto_size {
            self.calculate_size();
        }
        self
    }

    /// Returns the border thickness (0 for invisible borders)
    fn border_thickness(&self) -> u16 {
        match self.border_style {
            BorderStyle::None => 0,
            BorderStyle::Visible(_) => 1,
        }
    }

    /// Updates fullscreen container size to match terminal dimensions
    pub fn update_fullscreen_size(&mut self, terminal_width: u16, terminal_height: u16) {
        if self.fullscreen {
            self.width = terminal_width;
            self.height = terminal_height;
        }
    }

    /// Calculates the content area dimensions (excluding borders and padding)
    fn get_content_area(&self) -> (u16, u16, u16, u16) {
        let border_thickness = self.border_thickness();
        let content_x = self.x + border_thickness + self.padding.left;
        let content_y = self.y + border_thickness + self.padding.top;

        let content_width = self
            .width
            .saturating_sub(border_thickness * 2)
            .saturating_sub(self.padding.horizontal_total());
        let content_height = self
            .height
            .saturating_sub(border_thickness * 2)
            .saturating_sub(self.padding.vertical_total());

        (content_x, content_y, content_width, content_height)
    }

    /// Automatically calculates container size based on children
    fn calculate_size(&mut self) {
        if self.children.is_empty() {
            let border_thickness = self.border_thickness();
            self.width = border_thickness * 2 + self.padding.horizontal_total();
            self.height = border_thickness * 2 + self.padding.vertical_total();
            return;
        }

        let border_thickness = self.border_thickness();
        let mut required_width = 0u16;
        let mut required_height = 0u16;

        match self.layout_direction {
            LayoutDirection::Vertical => {
                // Width: maximum child width
                // Height: sum of all child heights + spacing
                for (i, child) in self.children.iter().enumerate() {
                    let (child_width, child_height) = child.get_size();
                    required_width = required_width.max(child_width);
                    required_height += child_height;

                    if i < self.children.len() - 1 {
                        required_height += self.child_spacing;
                    }
                }
            }
            LayoutDirection::Horizontal => {
                // Width: sum of all child widths + spacing
                // Height: maximum child height
                for (i, child) in self.children.iter().enumerate() {
                    let (child_width, child_height) = child.get_size();
                    required_width += child_width;
                    required_height = required_height.max(child_height);

                    if i < self.children.len() - 1 {
                        required_width += self.child_spacing;
                    }
                }
            }
        }

        self.width = required_width + (border_thickness * 2) + self.padding.horizontal_total();
        self.height = required_height + (border_thickness * 2) + self.padding.vertical_total();
    }

    /// Draws the border if it's visible
    fn draw_border(&self, window: &mut dyn Window) -> Result<()> {
        if let BorderStyle::Visible(border_chars) = &self.border_style {
            let mut draw_colored = |y: u16, x: u16, ch: char| -> Result<()> {
                if let Some(color) = self.border_color {
                    window.write_str_colored(y, x, &ch.to_string(), color)
                } else {
                    window.write_str(y, x, &ch.to_string())
                }
            };

            // Draw corners
            draw_colored(self.y, self.x, border_chars.top_left)?;
            draw_colored(self.y, self.x + self.width - 1, border_chars.top_right)?;
            draw_colored(self.y + self.height - 1, self.x, border_chars.bottom_left)?;
            draw_colored(
                self.y + self.height - 1,
                self.x + self.width - 1,
                border_chars.bottom_right,
            )?;

            // Draw horizontal borders
            for x in 1..self.width - 1 {
                draw_colored(self.y, self.x + x, border_chars.horizontal)?;
                draw_colored(
                    self.y + self.height - 1,
                    self.x + x,
                    border_chars.horizontal,
                )?;
            }

            // Draw vertical borders
            for y in 1..self.height - 1 {
                draw_colored(self.y + y, self.x, border_chars.vertical)?;
                draw_colored(self.y + y, self.x + self.width - 1, border_chars.vertical)?;
            }
        }
        Ok(())
    }

    /// Layouts and draws all child widgets
    fn draw_children(&self, window: &mut dyn Window) -> Result<()> {
        let (content_x, content_y, content_width, content_height) = self.get_content_area();

        // Calculate total content size for auto-centering
        let (total_content_width, total_content_height) =
            if matches!(self.content_alignment, ContentAlignment::AutoCenter) {
                self.calculate_total_content_size()
            } else {
                (0, 0) // Not needed for normal alignment
            };

        // Calculate centering offsets for the entire content block
        let (start_x, start_y) = match self.content_alignment {
            ContentAlignment::Normal => (0, 0),
            ContentAlignment::AutoCenter => {
                let offset_x = match self.layout_direction {
                    LayoutDirection::Vertical => {
                        // For vertical layout, center the widest child horizontally
                        if total_content_width < content_width {
                            (content_width - total_content_width) / 2
                        } else {
                            0
                        }
                    }
                    LayoutDirection::Horizontal => {
                        // For horizontal layout, center the entire content block
                        if total_content_width < content_width {
                            (content_width - total_content_width) / 2
                        } else {
                            0
                        }
                    }
                };
                let offset_y = if total_content_height < content_height {
                    (content_height - total_content_height) / 2
                } else {
                    0
                };
                (offset_x, offset_y)
            }
        };

        let mut current_x = start_x;
        let mut current_y = start_y;

        for (i, child) in self.children.iter().enumerate() {
            let (child_width, child_height) = child.get_size();

            // Calculate final child position
            let (child_x, child_y) = match self.content_alignment {
                ContentAlignment::Normal => (current_x, current_y),
                ContentAlignment::AutoCenter => {
                    match self.layout_direction {
                        LayoutDirection::Vertical => {
                            // For vertical layout in auto-center mode, center each child individually
                            // but ensure precise centering calculation
                            let centered_x = if child_width < content_width {
                                let available_space = content_width - child_width;
                                available_space / 2
                            } else {
                                0
                            };
                            (centered_x, current_y)
                        }
                        LayoutDirection::Horizontal => {
                            // For horizontal layout, use calculated positions
                            (current_x, start_y)
                        }
                    }
                }
            };

            // Create a window view for the child within our content area
            let mut child_window = WindowView {
                window,
                x_offset: content_x + child_x,
                y_offset: content_y + child_y,
                width: content_width.saturating_sub(child_x),
                height: content_height.saturating_sub(child_y),
            };

            // Draw the child widget
            child.draw(&mut child_window)?;

            // Update position for next child
            match self.layout_direction {
                LayoutDirection::Vertical => {
                    current_y += child_height;
                    if i < self.children.len() - 1 {
                        current_y += self.child_spacing;
                    }
                }
                LayoutDirection::Horizontal => {
                    current_x += child_width;
                    if i < self.children.len() - 1 {
                        current_x += self.child_spacing;
                    }
                }
            }
        }

        Ok(())
    }

    /// Calculates the total size of all content for centering purposes
    fn calculate_total_content_size(&self) -> (u16, u16) {
        if self.children.is_empty() {
            return (0, 0);
        }

        let mut total_width = 0u16;
        let mut total_height = 0u16;

        match self.layout_direction {
            LayoutDirection::Vertical => {
                // Width: maximum child width
                // Height: sum of all child heights + spacing
                for (i, child) in self.children.iter().enumerate() {
                    let (child_width, child_height) = child.get_size();
                    total_width = total_width.max(child_width);
                    total_height += child_height;

                    if i < self.children.len() - 1 {
                        total_height += self.child_spacing;
                    }
                }
            }
            LayoutDirection::Horizontal => {
                // Width: sum of all child widths + spacing
                // Height: maximum child height
                for (i, child) in self.children.iter().enumerate() {
                    let (child_width, child_height) = child.get_size();
                    total_width += child_width;
                    total_height = total_height.max(child_height);

                    if i < self.children.len() - 1 {
                        total_width += self.child_spacing;
                    }
                }
            }
        }

        (total_width, total_height)
    }
}

impl Widget for Container {
    fn draw(&self, window: &mut dyn Window) -> Result<()> {
        // For fullscreen containers, we assume they've been properly sized externally
        // before calling draw(). The draw() method shouldn't mutate the container.

        // Draw border first (if visible)
        self.draw_border(window)?;

        // Then draw children
        self.draw_children(window)?;

        Ok(())
    }

    fn get_size(&self) -> (u16, u16) {
        // For fullscreen containers that haven't been sized yet, return terminal size
        if self.fullscreen && (self.width == 0 || self.height == 0) {
            // This is a fallback - ideally update_fullscreen_size should be called first
            (80, 24) // Default terminal size
        } else {
            (self.width, self.height)
        }
    }

    fn get_position(&self) -> (u16, u16) {
        (self.x, self.y)
    }
}

// Convenience constructors for common patterns
impl Container {
    /// Creates a simple div-like container with no border
    pub fn div() -> Self {
        Self::new(0, 0, 0, 0).without_border()
    }

    /// Creates a bordered panel-like container
    pub fn panel() -> Self {
        Self::new(0, 0, 0, 0)
            .with_border(BorderChars::single_line())
            .with_padding(1)
    }

    /// Creates a card-like container with double border
    pub fn card() -> Self {
        Self::new(0, 0, 0, 0)
            .with_border(BorderChars::double_line())
            .with_padding(2)
    }

    /// Creates a container that centers a single text widget horizontally
    /// This is a convenience method for the common pattern of centering text
    pub fn centered_text(text: impl Into<String>, terminal_width: u16) -> Self {
        use crate::widgets::Text;

        let text_string = text.into();
        let text_len = text_string.chars().count() as u16;
        let left_padding = if terminal_width > text_len {
            (terminal_width - text_len) / 2
        } else {
            0
        };

        Self::div()
            .add_child(Text::new(text_string))
            .with_padding_config(Padding::custom(0, 0, 0, left_padding))
    }

    /// Creates a container that centers colored text horizontally
    pub fn centered_colored_text(
        text: impl Into<String>,
        color: crate::Color,
        terminal_width: u16,
    ) -> Self {
        use crate::widgets::Text;

        let text_string = text.into();
        let text_len = text_string.chars().count() as u16;
        let left_padding = if terminal_width > text_len {
            (terminal_width - text_len) / 2
        } else {
            0
        };

        Self::div()
            .add_child(Text::new(text_string).with_text_color(color))
            .with_padding_config(Padding::custom(0, 0, 0, left_padding))
    }
}