termtui 0.1.0

A framework for building beautiful, responsive terminal user interfaces with a DOM-style hierarchical approach
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
use crate::style::TextStyle;
use crate::{Color, TextWrap};

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

/// A span of text with optional styling
#[derive(Debug, Clone, Default, PartialEq)]
pub struct TextSpan {
    pub content: String,
    pub style: Option<TextStyle>,
    /// Internal flag to preserve cursor during wrapping
    #[doc(hidden)]
    pub is_cursor: bool,
}

/// Rich text with multiple styled segments for inline styling
#[derive(Debug, Clone, PartialEq)]
pub struct RichText {
    pub spans: Vec<TextSpan>,
    pub style: Option<TextStyle>, // For top-level styling like wrapping
}

//--------------------------------------------------------------------------------------------------
// Methods
//--------------------------------------------------------------------------------------------------

impl RichText {
    /// Creates a new empty RichText
    pub fn new() -> Self {
        Self {
            spans: Vec::new(),
            style: None,
        }
    }

    /// Creates RichText with a cursor at the specified position
    /// The cursor style will be preserved even after text wrapping
    /// Used internally by TextInput component
    pub fn with_cursor(text: &str, cursor_pos: usize, cursor_style: TextStyle) -> Self {
        let mut spans = Vec::new();
        let chars: Vec<char> = text.chars().collect();
        let char_count = chars.len();

        // Add text before cursor
        if cursor_pos > 0 && cursor_pos <= char_count {
            let before: String = chars[..cursor_pos].iter().collect();
            spans.push(TextSpan {
                content: before,
                style: None,
                is_cursor: false,
            });
        }

        // Add cursor character or space at end
        if cursor_pos < char_count {
            // Cursor on a character
            spans.push(TextSpan {
                content: chars[cursor_pos].to_string(),
                style: Some(cursor_style.clone()),
                is_cursor: true, // Mark as cursor span
            });
            // Add text after cursor
            if cursor_pos + 1 < char_count {
                let after: String = chars[cursor_pos + 1..].iter().collect();
                spans.push(TextSpan {
                    content: after,
                    style: None,
                    is_cursor: false,
                });
            }
        } else {
            // Cursor at end - show space with cursor style
            spans.push(TextSpan {
                content: " ".to_string(),
                style: Some(cursor_style),
                is_cursor: true, // Mark as cursor span
            });
        }

        Self { spans, style: None }
    }

    /// Adds a plain text span
    pub fn text(mut self, content: impl Into<String>) -> Self {
        self.spans.push(TextSpan {
            content: content.into(),
            style: None,
            is_cursor: false,
        });
        self
    }

    /// Adds a colored text span
    pub fn colored(mut self, content: impl Into<String>, color: Color) -> Self {
        self.spans.push(TextSpan {
            content: content.into(),
            style: Some(TextStyle {
                color: Some(color),
                ..Default::default()
            }),
            is_cursor: false,
        });
        self
    }

    /// Adds a bold text span
    pub fn bold(mut self, content: impl Into<String>) -> Self {
        self.spans.push(TextSpan {
            content: content.into(),
            style: Some(TextStyle {
                bold: Some(true),
                ..Default::default()
            }),
            is_cursor: false,
        });
        self
    }

    /// Adds an italic text span
    pub fn italic(mut self, content: impl Into<String>) -> Self {
        self.spans.push(TextSpan {
            content: content.into(),
            style: Some(TextStyle {
                italic: Some(true),
                ..Default::default()
            }),
            is_cursor: false,
        });
        self
    }

    /// Adds a text span with custom style
    pub fn styled(mut self, content: impl Into<String>, style: TextStyle) -> Self {
        self.spans.push(TextSpan {
            content: content.into(),
            style: Some(style),
            is_cursor: false,
        });
        self
    }

    /// Sets the text wrapping mode
    pub fn wrap(mut self, wrap: TextWrap) -> Self {
        self.style.get_or_insert(TextStyle::default()).wrap = Some(wrap);
        self
    }

    /// Sets the color for all spans that don't already have a color
    pub fn color(mut self, color: Color) -> Self {
        for span in &mut self.spans {
            let style = span.style.get_or_insert(TextStyle::default());
            if style.color.is_none() {
                style.color = Some(color);
            }
        }
        self
    }

    /// Sets the background color for all spans
    pub fn background(mut self, color: Color) -> Self {
        for span in &mut self.spans {
            let style = span.style.get_or_insert(TextStyle::default());
            if style.background.is_none() {
                style.background = Some(color);
            }
        }
        self
    }

    /// Makes all spans bold
    pub fn bold_all(mut self) -> Self {
        for span in &mut self.spans {
            let style = span.style.get_or_insert(TextStyle::default());
            if style.bold.is_none() {
                style.bold = Some(true);
            }
        }
        self
    }

    /// Makes all spans italic
    pub fn italic_all(mut self) -> Self {
        for span in &mut self.spans {
            let style = span.style.get_or_insert(TextStyle::default());
            if style.italic.is_none() {
                style.italic = Some(true);
            }
        }
        self
    }

    /// Makes all spans underlined
    pub fn underline_all(mut self) -> Self {
        for span in &mut self.spans {
            let style = span.style.get_or_insert(TextStyle::default());
            if style.underline.is_none() {
                style.underline = Some(true);
            }
        }
        self
    }

    /// Returns the concatenated content of all spans
    pub fn content(&self) -> String {
        self.spans
            .iter()
            .map(|span| span.content.as_str())
            .collect()
    }

    /// Returns true if there are no spans or all spans are empty
    pub fn is_empty(&self) -> bool {
        self.spans.is_empty() || self.spans.iter().all(|span| span.content.is_empty())
    }

    /// Clears all spans
    pub fn clear(&mut self) {
        self.spans.clear();
    }

    /// Appends another RichText's spans to this one
    pub fn append(&mut self, other: &mut RichText) {
        self.spans.append(&mut other.spans);
    }
}

//--------------------------------------------------------------------------------------------------
// Trait Implementations
//--------------------------------------------------------------------------------------------------

impl Default for RichText {
    fn default() -> Self {
        Self::new()
    }
}

impl From<String> for RichText {
    fn from(s: String) -> Self {
        Self::new().text(s)
    }
}

impl From<&str> for RichText {
    fn from(s: &str) -> Self {
        Self::new().text(s)
    }
}

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

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

    #[test]
    fn test_rich_text_creation() {
        let rich = RichText::new()
            .text("Hello ")
            .colored("world", Color::Red)
            .text("!");

        assert_eq!(rich.spans.len(), 3);
        assert_eq!(rich.spans[0].content, "Hello ");
        assert_eq!(rich.spans[1].content, "world");
        assert_eq!(rich.spans[2].content, "!");
        assert_eq!(
            rich.spans[1].style.as_ref().unwrap().color,
            Some(Color::Red)
        );
    }

    #[test]
    fn test_rich_text_bold_italic() {
        let rich = RichText::new()
            .text("Normal ")
            .bold("Bold")
            .text(" ")
            .italic("Italic");

        assert_eq!(rich.spans.len(), 4);
        assert_eq!(rich.spans[1].style.as_ref().unwrap().bold, Some(true));
        assert_eq!(rich.spans[3].style.as_ref().unwrap().italic, Some(true));
    }

    #[test]
    fn test_rich_text_with_cursor() {
        // Cursor in middle
        let rich = RichText::with_cursor(
            "Hello",
            2,
            TextStyle {
                background: Some(Color::Blue),
                ..Default::default()
            },
        );

        assert_eq!(rich.spans.len(), 3);
        assert_eq!(rich.spans[0].content, "He");
        assert_eq!(rich.spans[1].content, "l");
        assert_eq!(rich.spans[2].content, "lo");
        assert_eq!(
            rich.spans[1].style.as_ref().unwrap().background,
            Some(Color::Blue)
        );

        // Cursor at end
        let rich_end = RichText::with_cursor(
            "Hi",
            2,
            TextStyle {
                background: Some(Color::Green),
                ..Default::default()
            },
        );

        assert_eq!(rich_end.spans.len(), 2);
        assert_eq!(rich_end.spans[0].content, "Hi");
        assert_eq!(rich_end.spans[1].content, " ");
        assert_eq!(
            rich_end.spans[1].style.as_ref().unwrap().background,
            Some(Color::Green)
        );
    }

    #[test]
    fn test_top_level_styling_methods() {
        let rich = RichText::new()
            .text("First")
            .text(" ")
            .text("Second")
            .color(Color::Yellow)
            .background(Color::Black);

        // All spans should have yellow text on black background
        for span in &rich.spans {
            assert_eq!(span.style.as_ref().unwrap().color, Some(Color::Yellow));
            assert_eq!(span.style.as_ref().unwrap().background, Some(Color::Black));
        }
    }

    #[test]
    fn test_rich_text_bold_all() {
        let rich = RichText::new()
            .text("One")
            .colored("Two", Color::Red)
            .text("Three")
            .bold_all();

        // All spans should be bold
        for span in &rich.spans {
            assert_eq!(span.style.as_ref().unwrap().bold, Some(true));
        }
        // Second span should retain its color
        assert_eq!(
            rich.spans[1].style.as_ref().unwrap().color,
            Some(Color::Red)
        );
    }

    #[test]
    fn test_rich_text_wrap() {
        let rich = RichText::new()
            .text("This is wrapped text")
            .wrap(TextWrap::Word);

        assert!(rich.style.is_some());
        assert_eq!(rich.style.as_ref().unwrap().wrap, Some(TextWrap::Word));
    }

    #[test]
    fn test_rich_text_helper_methods() {
        let mut rich = RichText::new().text("Hello").text(" ").text("World");

        // Test content()
        assert_eq!(rich.content(), "Hello World");

        // Test is_empty()
        assert!(!rich.is_empty());

        // Test clear()
        rich.clear();
        assert!(rich.is_empty());
        assert_eq!(rich.content(), "");

        // Test append()
        let mut rich1 = RichText::new().text("First");
        let mut rich2 = RichText::new().colored("Second", Color::Blue);
        rich1.append(&mut rich2);
        assert_eq!(rich1.spans.len(), 2);
        assert_eq!(rich1.content(), "FirstSecond");
        assert!(rich2.is_empty());
    }

    #[test]
    fn test_rich_text_from_traits() {
        // From String
        let from_string: RichText = String::from("test string").into();
        assert_eq!(from_string.spans.len(), 1);
        assert_eq!(from_string.content(), "test string");

        // From &str
        let from_str: RichText = "test str".into();
        assert_eq!(from_str.spans.len(), 1);
        assert_eq!(from_str.content(), "test str");
    }

    #[test]
    fn test_rich_text_default() {
        let rich = RichText::default();
        assert!(rich.is_empty());
        assert_eq!(rich.content(), "");
    }
}