rnk 0.19.1

A React-like declarative terminal UI framework for Rust, inspired by Ink and Bubbletea
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
//! Text component - Text rendering with styles
//!
//! Supports both single-style text and multi-style text via Spans.
//!
//! # Examples
//!
//! Single style:
//! ```ignore
//! Text::new("Hello World").color(Color::Green).bold()
//! ```
//!
//! Multiple styles (Spans):
//! ```ignore
//! Text::spans(vec![
//!     Span::new("Hello ").color(Color::White),
//!     Span::new("World").color(Color::Green).bold(),
//! ])
//! ```

use crate::core::{Color, Element, ElementType, Style, TextWrap};

/// Generate chainable style setter methods for a type with a `style: Style` field.
/// Each method takes `mut self`, sets the style field, and returns `self`.
macro_rules! style_setters {
    // Color setter: fn name(mut self, color: Color) -> Self
    (color $name:ident => $field:ident, $doc:literal) => {
        #[doc = $doc]
        pub fn $name(mut self, color: Color) -> Self {
            self.style.$field = Some(color);
            self
        }
    };
    // Bool setter: fn name(mut self) -> Self
    (bool $name:ident => $field:ident, $doc:literal) => {
        #[doc = $doc]
        pub fn $name(mut self) -> Self {
            self.style.$field = true;
            self
        }
    };
}

/// Generate chainable style methods for Text that also propagate to child spans.
/// Color methods only propagate when the span doesn't already have that color set.
/// Bool methods propagate unconditionally.
macro_rules! text_style_setters {
    (color $name:ident => $field:ident, $doc:literal) => {
        #[doc = $doc]
        pub fn $name(mut self, color: Color) -> Self {
            self.style.$field = Some(color);
            self.for_each_span_mut(|span| {
                if span.style.$field.is_none() {
                    span.style.$field = Some(color);
                }
            });
            self
        }
    };
    (bool $name:ident => $field:ident, $doc:literal) => {
        #[doc = $doc]
        pub fn $name(mut self) -> Self {
            self.style.$field = true;
            self.for_each_span_mut(|span| span.style.$field = true);
            self
        }
    };
}

/// A styled text fragment
///
/// Span represents a piece of text with its own styling.
/// Multiple Spans can be combined in a Text component to create
/// rich text with mixed styles on a single line.
#[derive(Debug, Clone)]
pub struct Span {
    /// The text content
    pub content: String,
    /// The style for this span
    pub style: Style,
}

impl Span {
    /// Create a new Span with content
    pub fn new(content: impl Into<String>) -> Self {
        Self {
            content: content.into(),
            style: Style::new(),
        }
    }

    /// Create an unstyled Span (raw text)
    pub fn raw(content: impl Into<String>) -> Self {
        Self::new(content)
    }

    /// Create a styled Span
    pub fn styled(content: impl Into<String>, style: Style) -> Self {
        Self {
            content: content.into(),
            style,
        }
    }

    // === Style methods (chainable) ===

    style_setters!(color color => color, "Set text color");
    style_setters!(color background => background_color, "Set background color");
    style_setters!(bool bold => bold, "Set bold");
    style_setters!(bool italic => italic, "Set italic");
    style_setters!(bool underline => underline, "Set underline");
    style_setters!(bool strikethrough => strikethrough, "Set strikethrough");
    style_setters!(bool dim => dim, "Set dim");
    style_setters!(bool inverse => inverse, "Set inverse");

    /// Set foreground color (alias for color)
    pub fn fg(self, color: Color) -> Self {
        self.color(color)
    }

    /// Set background color (alias)
    pub fn bg(self, color: Color) -> Self {
        self.background(color)
    }

    /// Get the display width of this span
    pub fn width(&self) -> usize {
        use unicode_width::UnicodeWidthStr;
        self.content.width()
    }
}

impl<T: Into<String>> From<T> for Span {
    fn from(s: T) -> Self {
        Span::new(s)
    }
}

/// A line of text composed of multiple Spans
#[derive(Debug, Clone, Default)]
pub struct Line {
    /// The spans that make up this line
    pub spans: Vec<Span>,
}

impl Line {
    /// Create a new empty Line
    pub fn new() -> Self {
        Self { spans: Vec::new() }
    }

    /// Create a Line from spans
    pub fn from_spans(spans: Vec<Span>) -> Self {
        Self { spans }
    }

    /// Create a Line from a single string (raw text)
    pub fn raw(content: impl Into<String>) -> Self {
        Self {
            spans: vec![Span::new(content)],
        }
    }

    /// Add a span to this line
    pub fn span(mut self, span: impl Into<Span>) -> Self {
        self.spans.push(span.into());
        self
    }

    /// Get the display width of this line
    pub fn width(&self) -> usize {
        self.spans.iter().map(|s| s.width()).sum()
    }

    /// Check if the line is empty
    pub fn is_empty(&self) -> bool {
        self.spans.is_empty() || self.spans.iter().all(|s| s.content.is_empty())
    }
}

impl From<&str> for Line {
    fn from(s: &str) -> Self {
        Line::from_spans(vec![Span::new(s)])
    }
}

impl From<String> for Line {
    fn from(s: String) -> Self {
        Line::from_spans(vec![Span::new(s)])
    }
}

impl From<Span> for Line {
    fn from(s: Span) -> Self {
        Line::from_spans(vec![s])
    }
}

impl From<Vec<Span>> for Line {
    fn from(spans: Vec<Span>) -> Self {
        Line::from_spans(spans)
    }
}

/// Text component builder
///
/// Text can be created in two ways:
/// 1. Simple text with a single style: `Text::new("Hello").color(Color::Green)`
/// 2. Rich text with multiple spans: `Text::spans(vec![Span::new("Hello").bold(), Span::new(" World")])`
#[derive(Debug, Clone)]
pub struct Text {
    /// The lines of text (each line contains spans)
    lines: Vec<Line>,
    /// Default style applied to spans without explicit styling
    style: Style,
    /// Key for reconciliation
    key: Option<String>,
}

impl Text {
    /// Create a new Text with content (single style)
    pub fn new(content: impl Into<String>) -> Self {
        let content_str: String = content.into();
        let lines: Vec<Line> = content_str.lines().map(Line::raw).collect();

        Self {
            lines: if lines.is_empty() {
                vec![Line::raw("")]
            } else {
                lines
            },
            style: Style::new(),
            key: None,
        }
    }

    /// Create a new Text from multiple spans (rich text, single line)
    pub fn spans(spans: Vec<Span>) -> Self {
        Self {
            lines: vec![Line::from_spans(spans)],
            style: Style::new(),
            key: None,
        }
    }

    /// Create a new Text from a Line
    pub fn line(line: Line) -> Self {
        Self {
            lines: vec![line],
            style: Style::new(),
            key: None,
        }
    }

    /// Create a new Text from multiple Lines
    pub fn from_lines(lines: Vec<Line>) -> Self {
        Self {
            lines,
            style: Style::new(),
            key: None,
        }
    }

    /// Set key for reconciliation
    pub fn key(mut self, key: impl Into<String>) -> Self {
        self.key = Some(key.into());
        self
    }

    /// Get the lines
    pub fn get_lines(&self) -> &[Line] {
        &self.lines
    }

    /// Apply a mutation to every span in the text.
    fn for_each_span_mut(&mut self, mut apply: impl FnMut(&mut Span)) {
        for line in &mut self.lines {
            for span in &mut line.spans {
                apply(span);
            }
        }
    }

    // === Text styles (applied as default to all spans) ===

    text_style_setters!(color color => color, "Set text color");
    text_style_setters!(color background => background_color, "Set background color");
    text_style_setters!(bool bold => bold, "Set bold");
    text_style_setters!(bool italic => italic, "Set italic");
    text_style_setters!(bool underline => underline, "Set underline");
    text_style_setters!(bool strikethrough => strikethrough, "Set strikethrough");
    text_style_setters!(bool dim => dim, "Set dim (less bright)");
    text_style_setters!(bool inverse => inverse, "Set inverse (swap foreground and background)");

    /// Alias for background
    pub fn bg(self, color: Color) -> Self {
        self.background(color)
    }

    /// Set text wrap behavior
    pub fn wrap(mut self, wrap: TextWrap) -> Self {
        self.style.text_wrap = wrap;
        self
    }

    // === Convenience methods ===

    /// Apply error style (red color)
    pub fn error(self) -> Self {
        self.color(Color::Red)
    }

    /// Apply success style (green color)
    pub fn success(self) -> Self {
        self.color(Color::Green)
    }

    /// Apply warning style (yellow color)
    pub fn warning(self) -> Self {
        self.color(Color::Yellow)
    }

    /// Apply info style (blue color)
    pub fn info(self) -> Self {
        self.color(Color::Blue)
    }

    /// Apply muted style (dim)
    pub fn muted(self) -> Self {
        self.dim()
    }

    /// Convert to Element
    ///
    /// For simple text (single span per line), uses text_content.
    /// For rich text (multiple spans), stores spans in the element.
    pub fn into_element(self) -> Element {
        let mut element = Element::new(ElementType::Text);
        element.style = self.style;
        element.key = self.key;

        // Check if this is simple text (single span per line, no mixed styles)
        let is_simple = self.lines.len() == 1 && self.lines[0].spans.len() == 1;

        if is_simple {
            // Simple text: use text_content for backward compatibility
            element.text_content = Some(self.lines[0].spans[0].content.clone());
            // Merge span style into element style (span takes precedence)
            let span_style = &self.lines[0].spans[0].style;
            element.style = element.style.merge(span_style);
        } else {
            // Rich text: concatenate plain text for layout measurement
            let mut full_text = String::new();
            for (i, line) in self.lines.iter().enumerate() {
                if i > 0 {
                    full_text.push('\n');
                }
                for span in &line.spans {
                    full_text.push_str(&span.content);
                }
            }
            element.text_content = Some(full_text);
            // Store spans for styled rendering (renderer prioritizes spans over text_content)
            element.spans = Some(self.lines);
        }

        element
    }
}

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

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

    #[test]
    fn test_text_creation() {
        let element = Text::new("Hello").into_element();
        assert_eq!(element.get_text(), Some("Hello"));
    }

    #[test]
    fn test_text_styles() {
        let element = Text::new("Styled")
            .color(Color::Green)
            .bold()
            .underline()
            .into_element();

        assert_eq!(element.style.color, Some(Color::Green));
        assert!(element.style.bold);
        assert!(element.style.underline);
    }

    #[test]
    fn test_text_convenience_methods() {
        let error = Text::new("Error").error().into_element();
        assert_eq!(error.style.color, Some(Color::Red));

        let success = Text::new("Success").success().into_element();
        assert_eq!(success.style.color, Some(Color::Green));
    }

    #[test]
    fn test_span_creation() {
        let span = Span::new("Hello").color(Color::Green).bold();

        assert_eq!(span.content, "Hello");
        assert_eq!(span.style.color, Some(Color::Green));
        assert!(span.style.bold);
    }

    #[test]
    fn test_text_with_spans() {
        let text = Text::spans(vec![
            Span::new("Hello ").color(Color::White),
            Span::new("World").color(Color::Green).bold(),
        ]);

        assert_eq!(text.lines.len(), 1);
        assert_eq!(text.lines[0].spans.len(), 2);
        assert_eq!(text.lines[0].spans[0].content, "Hello ");
        assert_eq!(text.lines[0].spans[1].content, "World");
    }

    #[test]
    fn test_text_spans_element() {
        let element = Text::spans(vec![
            Span::new("Hello ").color(Color::White),
            Span::new("World").color(Color::Green),
        ])
        .into_element();

        // Should have spans, not simple text_content
        assert!(element.spans.is_some());
        let spans = element.spans.as_ref().unwrap();
        assert_eq!(spans.len(), 1);
        assert_eq!(spans[0].spans.len(), 2);
    }

    #[test]
    fn test_line_creation() {
        let line = Line::new()
            .span(Span::new("Part 1").color(Color::Red))
            .span(Span::new(" - "))
            .span(Span::new("Part 2").color(Color::Blue));

        assert_eq!(line.spans.len(), 3);
        assert_eq!(line.width(), 15); // "Part 1" (6) + " - " (3) + "Part 2" (6)
    }

    #[test]
    fn test_multiline_text() {
        let text = Text::from_lines(vec![
            Line::from_spans(vec![Span::new("Line 1").bold()]),
            Line::from_spans(vec![Span::new("Line 2").italic()]),
        ]);

        assert_eq!(text.lines.len(), 2);
    }
}