minui 0.3.2

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
//! # Text Widgets
//!
//! A comprehensive collection of text-based UI components for displaying and formatting
//! textual content in terminal applications. This module provides three primary widgets:
//! labels for titles and captions, standalone text widgets for simple content display,
//! and advanced multi-line text blocks with rich formatting capabilities.
//!
//! ## Features
//!
//! - **Multiple text widgets**: Label, Text, and TextBlock for different use cases
//! - **Flexible alignment**: Horizontal and vertical text positioning options
//! - **Advanced wrapping**: Character-level, word-aware, and no-wrap modes
//! - **Rich styling**: Color pairs and formatting options
//! - **Auto-sizing**: Automatic dimension calculation based on content
//! - **Container integration**: Seamless layout within MinUI's container system
//!
//! ## Widget Types
//!
//! ### Label
//! Simple, single-line text for titles, captions, and widget labeling. Ideal for
//! header text, form labels, and UI element identification.
//!
//! ### Text
//! Standalone text display widget for general content. Supports multi-line content
//! with basic alignment and color styling.
//!
//! ### TextBlock
//! Advanced multi-line text widget with sophisticated formatting options including
//! word wrapping, vertical alignment, and precise dimension control.
//!
//! ## Basic Usage
//!
//! ```rust
//! use minui::{Label, Text, TextBlock, Alignment, VerticalAlignment, TextWrapMode, Color};
//!
//! // Simple label for UI elements
//! let title = Label::new("Application Settings")
//!     .with_color(Some(Color::Cyan.into()));
//!
//! // Basic text content
//! let info = Text::new("Welcome to the application!\nPlease configure your preferences.")
//!     .with_alignment(Alignment::Center);
//!
//! // Advanced formatted text block
//! let content = TextBlock::new(40, 10, "Long content that will wrap nicely...")
//!     .with_wrap_mode(TextWrapMode::WrapWords)
//!     .with_vertical_alignment(VerticalAlignment::Middle);
//! ```
//!
//! ## Advanced Text Formatting
//!
//! ```rust
//! use minui::{TextBlock, TextWrapMode, VerticalAlignment, Alignment, ColorPair, Color};
//!
//! // Create a sophisticated text display
//! let formatted_text = TextBlock::new(50, 15,
//!     "This is a comprehensive example of advanced text formatting. \
//!      The text will wrap at word boundaries and be vertically centered \
//!      within the specified dimensions. Color styling enhances readability.")
//!     .with_wrap_mode(TextWrapMode::WrapWords)
//!     .with_vertical_alignment(VerticalAlignment::Middle)
//!     .with_alignment(Alignment::Left)
//!     .with_color(Some(ColorPair::new(Color::White, Color::Blue)));
//! ```
//!
//! ## Layout Integration
//!
//! ```rust
//! use minui::{Container, Label, Text, LayoutDirection};
//!
//! // Combine text widgets in layouts
//! let info_section = Container::new(LayoutDirection::Vertical)
//!     .add_child(Label::new("System Information").with_color(Some(Color::Green.into())))
//!     .add_child(Text::new("CPU: 45% usage\nMemory: 2.1GB / 8GB\nDisk: 250GB free"));
//! ```
//!
//! ## Text Wrapping Modes
//!
//! The TextBlock widget supports three wrapping strategies:
//!
//! - **None**: Content extending beyond width is clipped
//! - **Wrap**: Character-level wrapping at any position
//! - **WrapWords**: Intelligent word-boundary wrapping for readability
//!
//! Text widgets integrate seamlessly with MinUI's container-based layout system,
//! automatically positioning and sizing themselves within parent containers while
//! maintaining proper text formatting and alignment.

use super::Widget;
use crate::input::scroll::Scroller;
use crate::{Color, ColorPair, Result, Window};

/// How to align text horizontally
#[derive(Debug, Clone, Copy)]
pub enum Alignment {
    /// Align text to the left side
    Left,
    /// Center text horizontally
    Center,
    /// Align text to the right side
    Right,
}

/// How to align text vertically
#[derive(Debug, Clone, Copy)]
pub enum VerticalAlignment {
    /// Align text to the top of the widget area
    Top,
    /// Center text vertically within the widget area
    Middle,
    /// Align text to the bottom of the widget area
    Bottom,
}

/// How TextBlock should wrap long lines
#[derive(Debug, Clone, Copy)]
pub enum TextWrapMode {
    /// No text wrapping - content extending beyond width is clipped
    None,
    /// Character-level wrapping - text wraps at any character
    Wrap,
    /// Word-aware wrapping - text wraps at word boundaries
    WrapWords,
}

/// A simple label widget for titles, captions, and labeling other widgets.
///
/// Use this for labeling panels and containers. For standalone text content,
/// use the `Text` widget instead.
pub struct Label {
    /// The label text content
    text: String,
    /// Optional color styling for the text
    colors: Option<ColorPair>,
    /// Horizontal alignment of the text
    alignment: Alignment,
}

impl Label {
    /// Creates a new label with the given text
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            colors: None,
            alignment: Alignment::Left,
        }
    }

    /// Sets foreground and background colors
    pub fn with_color(mut self, colors: ColorPair) -> Self {
        self.colors = Some(colors);
        self
    }

    /// Sets just the text color
    pub fn with_text_color(mut self, color: Color) -> Self {
        self.colors = Some(ColorPair::new(color, Color::Transparent));
        self
    }

    /// Sets how the text is aligned horizontally
    pub fn with_alignment(mut self, alignment: Alignment) -> Self {
        self.alignment = alignment;
        self
    }

    /// Changes the label text
    pub fn set_text(&mut self, text: impl Into<String>) {
        self.text = text.into();
    }

    /// Returns the current text
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Returns the text length in characters
    pub fn get_length(&self) -> u16 {
        self.text.chars().count() as u16
    }

    fn calculate_aligned_x(&self, available_width: u16) -> u16 {
        let text_length = self.get_length();
        match self.alignment {
            Alignment::Left => 0,
            Alignment::Center => {
                if text_length < available_width {
                    (available_width - text_length) / 2
                } else {
                    0
                }
            }
            Alignment::Right => {
                if text_length < available_width {
                    available_width - text_length
                } else {
                    0
                }
            }
        }
    }
}

impl Widget for Label {
    fn draw(&self, window: &mut dyn Window) -> Result<()> {
        let (window_width, _) = window.get_size();
        let x_pos = self.calculate_aligned_x(window_width);

        match self.colors {
            Some(colors) => window.write_str_colored(0, x_pos, &self.text, colors),
            None => window.write_str(0, x_pos, &self.text),
        }
    }

    fn get_size(&self) -> (u16, u16) {
        (self.text.chars().count() as u16, 1)
    }

    fn get_position(&self) -> (u16, u16) {
        (0, 0) // Position is managed by parent container
    }
}

/// A standalone text widget for single-line content.
///
/// Use this for regular text content. Use `Label` for titles and captions.
pub struct Text {
    /// The text content to display
    text: String,
    /// Optional color styling for the text
    colors: Option<ColorPair>,
    /// Horizontal alignment of the text
    alignment: Alignment,
}

impl Text {
    /// Creates a new text widget
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            colors: None,
            alignment: Alignment::Left,
        }
    }

    /// Sets foreground and background colors
    pub fn with_color(mut self, colors: ColorPair) -> Self {
        self.colors = Some(colors);
        self
    }

    /// Sets just the text color
    pub fn with_text_color(mut self, color: Color) -> Self {
        self.colors = Some(ColorPair::new(color, Color::Transparent));
        self
    }

    /// Sets how the text is aligned horizontally
    pub fn with_alignment(mut self, alignment: Alignment) -> Self {
        self.alignment = alignment;
        self
    }

    /// Changes the text content
    pub fn set_text(&mut self, text: impl Into<String>) {
        self.text = text.into();
    }

    /// Returns the current text
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Returns the text length in characters
    pub fn get_length(&self) -> u16 {
        self.text.chars().count() as u16
    }

    fn calculate_aligned_x(&self, available_width: u16) -> u16 {
        let text_length = self.get_length();
        match self.alignment {
            Alignment::Left => 0,
            Alignment::Center => {
                if text_length < available_width {
                    (available_width - text_length) / 2
                } else {
                    0
                }
            }
            Alignment::Right => {
                if text_length < available_width {
                    available_width - text_length
                } else {
                    0
                }
            }
        }
    }
}

impl Widget for Text {
    fn draw(&self, window: &mut dyn Window) -> Result<()> {
        let (available_width, _) = window.get_size();
        let x_pos = self.calculate_aligned_x(available_width);

        match self.colors {
            Some(colors) => window.write_str_colored(0, x_pos, &self.text, colors),
            None => window.write_str(0, x_pos, &self.text),
        }
    }

    fn get_size(&self) -> (u16, u16) {
        (self.text.chars().count() as u16, 1)
    }

    fn get_position(&self) -> (u16, u16) {
        (0, 0) // Position is managed by parent container
    }
}

/// A multi-line text widget with wrapping and scrolling support.
///
/// Use this for longer text content that spans multiple lines.
pub struct TextBlock {
    /// Width of the text display area
    width: u16,
    /// Height of the text display area
    height: u16,
    /// The text content to display
    text: String,
    /// Optional color styling for the text
    colors: Option<ColorPair>,
    /// Text wrapping behavior
    wrap_mode: TextWrapMode,
    /// Horizontal text alignment
    h_align: Alignment,
    /// Vertical text alignment
    v_align: VerticalAlignment,
    /// Scroll state manager for displaying large content
    scroller: Scroller,
    /// Whether to show scroll indicators
    show_scroll_indicators: bool,
}

impl TextBlock {
    /// Creates a new TextBlock with the given size and content
    pub fn new(width: u16, height: u16, text: impl Into<String>) -> Self {
        Self {
            width,
            height,
            text: text.into(),
            colors: None,
            wrap_mode: TextWrapMode::Wrap,
            h_align: Alignment::Left,
            v_align: VerticalAlignment::Top,
            scroller: Scroller::new(),
            show_scroll_indicators: false,
        }
    }

    /// Creates a TextBlock that sizes itself to fit the content
    pub fn auto_sized(text: impl Into<String>) -> Self {
        let text = text.into();
        let lines: Vec<&str> = text.lines().collect();
        let width = lines.iter().map(|line| line.len()).max().unwrap_or(0) as u16;
        let height = lines.len() as u16;

        Self::new(width, height, text)
    }

    /// Creates a TextBlock with word wrapping that sizes itself to fit.
    ///
    /// Wraps text at word boundaries, then sizes the widget to fit the wrapped content.
    pub fn auto_sized_with_word_wrap(text: impl Into<String>, max_width: u16) -> Self {
        let text = text.into();
        let mut lines = Vec::new();
        let mut current_line = String::new();

        for word in text.split_whitespace() {
            let needed_space = if current_line.is_empty() {
                word.len()
            } else {
                current_line.len() + 1 + word.len()
            };

            if needed_space <= max_width as usize {
                if !current_line.is_empty() {
                    current_line.push(' ');
                }
                current_line.push_str(word);
            } else {
                if !current_line.is_empty() {
                    lines.push(current_line);
                }
                current_line = word.to_string();
            }
        }

        if !current_line.is_empty() {
            lines.push(current_line);
        }

        let actual_width = lines.iter().map(|line| line.len()).max().unwrap_or(0) as u16;
        let height = lines.len() as u16;

        let mut text_block = Self::new(actual_width, height, lines.join("\n"));
        text_block.wrap_mode = TextWrapMode::None; // Already wrapped, no need to re-wrap
        text_block
    }

    /// Sets the text colors
    pub fn with_colors(mut self, colors: ColorPair) -> Self {
        self.colors = Some(colors);
        self
    }

    /// Sets just the text color
    pub fn with_text_color(mut self, color: Color) -> Self {
        self.colors = Some(ColorPair::new(color, Color::Transparent));
        self
    }

    /// Sets how text should wrap
    pub fn with_wrap_mode(mut self, mode: TextWrapMode) -> Self {
        self.wrap_mode = mode;
        self
    }

    /// Enables word wrapping
    pub fn with_word_wrap(mut self) -> Self {
        self.wrap_mode = TextWrapMode::WrapWords;
        self
    }

    /// Sets horizontal and vertical alignment
    pub fn with_alignment(mut self, h_align: Alignment, v_align: VerticalAlignment) -> Self {
        self.h_align = h_align;
        self.v_align = v_align;
        self
    }

    /// Enables or disables scroll indicators
    pub fn with_scroll_indicators(mut self, show: bool) -> Self {
        self.show_scroll_indicators = show;
        self
    }

    /// Sets the scroll direction for the text block.
    ///
    /// # Arguments
    /// * `natural` - `true` for natural scrolling (default), `false` for inverted scrolling
    ///
    /// # Examples
    ///
    /// ```rust
    /// use minui::TextBlock;
    ///
    /// let text = TextBlock::new(40, 20, "Some content...")
    ///     .with_scroll_direction(false); // Inverted scrolling
    /// ```
    pub fn with_scroll_direction(mut self, natural: bool) -> Self {
        self.scroller.set_invert_scroll_vertical(!natural);
        self
    }

    /// Sets whether scroll direction is inverted for the text block.
    ///
    /// When enabled, scrolling direction is reversed (e.g., up becomes down).
    pub fn set_invert_scroll(&mut self, invert: bool) {
        self.scroller.set_invert_scroll_vertical(invert);
    }

    /// Returns whether scroll direction is inverted for the text block.
    pub fn is_scroll_inverted(&self) -> bool {
        self.scroller.is_scroll_vertical_inverted()
    }

    /// Scrolls to a specific line
    pub fn scroll_to(&mut self, line: u16) {
        let max_offset = self.max_scroll_offset();
        self.scroller.scroll_to(line, max_offset);
    }

    /// Scrolls by a relative amount (positive = down, negative = up)
    pub fn scroll_by(&mut self, delta: i16) {
        let max_offset = self.max_scroll_offset();
        self.scroller.scroll_by(delta, max_offset);
    }

    /// Scrolls to the top of the content
    pub fn scroll_to_top(&mut self) {
        self.scroller.scroll_to_top();
    }

    /// Scrolls to the bottom of the content
    pub fn scroll_to_bottom(&mut self) {
        let max_offset = self.max_scroll_offset();
        self.scroller.scroll_to_bottom(max_offset);
    }

    /// Returns the current scroll offset
    pub fn scroll_offset(&self) -> u16 {
        self.scroller.offset()
    }

    /// Returns the maximum valid scroll offset
    pub fn max_scroll_offset(&self) -> u16 {
        let lines = self.get_wrapped_lines();
        let total_lines = lines.len() as u16;
        total_lines.saturating_sub(self.height)
    }

    /// Returns whether the content can be scrolled
    pub fn can_scroll(&self) -> bool {
        let lines = self.get_wrapped_lines();
        lines.len() as u16 > self.height
    }

    /// Returns whether scrolling up is possible
    pub fn can_scroll_up(&self) -> bool {
        self.scroller.can_scroll_up()
    }

    /// Returns whether scrolling down is possible
    pub fn can_scroll_down(&self) -> bool {
        self.scroller.can_scroll_down(self.max_scroll_offset())
    }

    /// Handles a mouse scroll event and updates the scroll position
    ///
    /// Returns true if the scroll position changed
    pub fn handle_scroll_event(&mut self, delta: i8) -> bool {
        let max_offset = self.max_scroll_offset();
        self.scroller.handle_scroll_event(delta, max_offset)
    }

    /// Handles a mouse drag event on the TextBlock.
    /// If the drag is on the scrollbar, scrolls to that position.
    /// Returns true if the scroll position changed.
    ///
    /// # Arguments
    /// * `drag_x` - X coordinate of drag relative to TextBlock's top-left
    /// * `drag_y` - Y coordinate of drag relative to TextBlock's top-left
    pub fn handle_drag_event(&mut self, drag_x: u16, drag_y: u16) -> bool {
        if !self.can_scroll() {
            return false;
        }

        let scrollbar_x = self.width.saturating_sub(1);
        let max_scroll = self.max_scroll_offset();

        // Use dedicated drag method for smoother interaction
        self.scroller
            .handle_drag_event(drag_x, drag_y, scrollbar_x, self.height, 0, max_scroll)
    }

    /// Handles a mouse click event on the TextBlock.
    /// If the click is on the scrollbar, scrolls to that position.
    /// Returns true if the scroll position changed.
    ///
    /// # Arguments
    /// * `click_x` - X coordinate of click relative to TextBlock's top-left
    /// * `click_y` - Y coordinate of click relative to TextBlock's top-left
    pub fn handle_click_event(&mut self, click_x: u16, click_y: u16) -> bool {
        if !self.can_scroll() {
            return false;
        }

        let scrollbar_x = self.width.saturating_sub(1);
        let max_scroll = self.max_scroll_offset();

        // Check if click is on scrollbar
        if click_x == scrollbar_x && click_y < self.height {
            return self.scroller.handle_scrollbar_event(
                click_x,
                click_y,
                scrollbar_x,
                self.height,
                0,
                max_scroll,
            );
        }

        false
    }

    /// Returns the number of lines in the wrapped content
    pub fn line_count(&self) -> usize {
        self.get_wrapped_lines().len()
    }

    /// Returns the visible line range as (start, end)
    pub fn visible_range(&self) -> (u16, u16) {
        let start = self.scroller.offset();
        let end = (start + self.height).min(self.line_count() as u16);
        (start, end)
    }

    /// Changes the text content
    pub fn set_text(&mut self, text: impl Into<String>) {
        self.text = text.into();
        // Clamp scroll offset to new content bounds
        let max_offset = self.max_scroll_offset();
        self.scroller.set_offset(self.scroller.offset(), max_offset);
    }

    /// Returns the current text
    pub fn text(&self) -> &str {
        &self.text
    }

    fn get_wrapped_lines(&self) -> Vec<String> {
        match self.wrap_mode {
            TextWrapMode::None => self.text.lines().map(String::from).collect(),
            TextWrapMode::Wrap => self
                .text
                .chars()
                .collect::<Vec<_>>()
                .chunks(self.width as usize)
                .map(|chunk| chunk.iter().collect::<String>())
                .collect(),
            TextWrapMode::WrapWords => {
                let mut lines = Vec::new();
                let mut current_line = String::new();

                for word in self.text.split_whitespace() {
                    if current_line.len() + word.len() + 1 <= self.width as usize {
                        if !current_line.is_empty() {
                            current_line.push(' ');
                        }
                        current_line.push_str(word);
                    } else {
                        if !current_line.is_empty() {
                            lines.push(current_line);
                        }
                        current_line = word.to_string();
                    }
                }

                if !current_line.is_empty() {
                    lines.push(current_line);
                }

                lines
            }
        }
    }
}

impl Widget for TextBlock {
    fn draw(&self, window: &mut dyn Window) -> Result<()> {
        let lines = self.get_wrapped_lines();
        let (window_width, window_height) = window.get_size();

        // Calculate available dimensions (min of widget size and window size)
        let available_width = window_width.min(self.width);
        let available_height = window_height.min(self.height);

        // Calculate starting positions based on alignment
        let total_lines = lines.len().min(available_height as usize);
        let start_y = match self.v_align {
            VerticalAlignment::Top => 0,
            VerticalAlignment::Middle => {
                if total_lines < available_height as usize {
                    (available_height - total_lines as u16) / 2
                } else {
                    0
                }
            }
            VerticalAlignment::Bottom => {
                if total_lines < available_height as usize {
                    available_height - total_lines as u16
                } else {
                    0
                }
            }
        };

        // Get displayable lines with scroll offset
        let start_line = self.scroller.offset() as usize;
        let display_lines: Vec<String> = lines
            .into_iter()
            .skip(start_line)
            .take(available_height as usize)
            .collect();

        // Draw each line
        for (i, line) in display_lines.iter().enumerate() {
            let line_y = start_y + i as u16;
            if line_y >= available_height {
                break;
            }

            let line_x = match self.h_align {
                Alignment::Left => 0,
                Alignment::Center => {
                    if line.len() < available_width as usize {
                        (available_width - line.len() as u16) / 2
                    } else {
                        0
                    }
                }
                Alignment::Right => {
                    if line.len() < available_width as usize {
                        available_width - line.len() as u16
                    } else {
                        0
                    }
                }
            };

            if let Some(colors) = self.colors {
                window.write_str_colored(line_y, line_x, line, colors)?;
            } else {
                window.write_str(line_y, line_x, line)?;
            }
        }

        Ok(())
    }

    fn get_size(&self) -> (u16, u16) {
        (self.width, self.height)
    }

    fn get_position(&self) -> (u16, u16) {
        (0, 0) // Position is managed by parent container
    }
}