revue 2.71.1

A Vue-style TUI framework for Rust with CSS styling
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
//! Rich text widget with styled spans and hyperlinks
//!
//! Provides rich text rendering with inline styling, similar to Textual's Rich library.
//!
//! # Examples
//!
//! ```ignore
//! use revue::widget::{RichText, Span, Style};
//!
//! // Builder API
//! let text = RichText::new()
//!     .push("Hello ", Style::new().bold())
//!     .push("World", Style::new().fg(Color::GREEN))
//!     .push_link("Click here", "https://example.com");
//!
//! // Markup API
//! let text = RichText::markup("[bold]Hello[/] [green]World[/]");
//! ```

use crate::render::{Cell, Modifier};
use crate::style::Color;
use crate::widget::traits::{RenderContext, View, WidgetProps};
use crate::{impl_props_builders, impl_styled_view};

/// Text style for spans
#[derive(Clone, Debug, Default)]
pub struct Style {
    /// Foreground color
    pub fg: Option<Color>,
    /// Background color
    pub bg: Option<Color>,
    /// Bold text
    pub bold: bool,
    /// Italic text
    pub italic: bool,
    /// Underlined text
    pub underline: bool,
    /// Dim text
    pub dim: bool,
    /// Strikethrough text
    pub strikethrough: bool,
    /// Reverse video (swap fg/bg)
    pub reverse: bool,
}

impl Style {
    /// Create a new empty style
    pub fn new() -> Self {
        Self::default()
    }

    /// Set foreground color
    pub fn fg(mut self, color: Color) -> Self {
        self.fg = Some(color);
        self
    }

    /// Set background color
    pub fn bg(mut self, color: Color) -> Self {
        self.bg = Some(color);
        self
    }

    /// Set bold
    pub fn bold(mut self) -> Self {
        self.bold = true;
        self
    }

    /// Set italic
    pub fn italic(mut self) -> Self {
        self.italic = true;
        self
    }

    /// Set underline
    pub fn underline(mut self) -> Self {
        self.underline = true;
        self
    }

    /// Set dim
    pub fn dim(mut self) -> Self {
        self.dim = true;
        self
    }

    /// Set strikethrough
    pub fn strikethrough(mut self) -> Self {
        self.strikethrough = true;
        self
    }

    /// Set reverse video (swap foreground/background)
    pub fn reverse(mut self) -> Self {
        self.reverse = true;
        self
    }

    // ─────────────────────────────────────────────────────────────────────────
    // Preset styles
    // ─────────────────────────────────────────────────────────────────────────

    /// Red foreground
    pub fn red() -> Self {
        Self::new().fg(Color::RED)
    }

    /// Green foreground
    pub fn green() -> Self {
        Self::new().fg(Color::GREEN)
    }

    /// Blue foreground
    pub fn blue() -> Self {
        Self::new().fg(Color::BLUE)
    }

    /// Yellow foreground
    pub fn yellow() -> Self {
        Self::new().fg(Color::YELLOW)
    }

    /// Cyan foreground
    pub fn cyan() -> Self {
        Self::new().fg(Color::CYAN)
    }

    /// Magenta foreground
    pub fn magenta() -> Self {
        Self::new().fg(Color::MAGENTA)
    }

    /// White foreground
    pub fn white() -> Self {
        Self::new().fg(Color::WHITE)
    }

    /// Get modifier flags
    fn to_modifier(&self) -> Modifier {
        let mut m = Modifier::empty();
        if self.bold {
            m |= Modifier::BOLD;
        }
        if self.italic {
            m |= Modifier::ITALIC;
        }
        if self.underline {
            m |= Modifier::UNDERLINE;
        }
        if self.dim {
            m |= Modifier::DIM;
        }
        if self.strikethrough {
            m |= Modifier::CROSSED_OUT;
        }
        if self.reverse {
            m |= Modifier::REVERSE;
        }
        m
    }
}

/// A styled text span
#[derive(Clone, Debug)]
pub struct Span {
    /// Text content
    pub text: String,
    /// Style
    pub style: Style,
    /// Optional hyperlink URL
    pub link: Option<String>,
}

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

    /// Create a styled span
    pub fn styled(text: impl Into<String>, style: Style) -> Self {
        Self {
            text: text.into(),
            style,
            link: None,
        }
    }

    /// Create a hyperlink span
    pub fn link(text: impl Into<String>, url: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            style: Style::new().fg(Color::CYAN).underline(),
            link: Some(url.into()),
        }
    }

    /// Set style
    pub fn style(mut self, style: Style) -> Self {
        self.style = style;
        self
    }

    /// Set hyperlink
    pub fn href(mut self, url: impl Into<String>) -> Self {
        self.link = Some(url.into());
        self
    }

    /// Get text width
    pub fn width(&self) -> usize {
        unicode_width::UnicodeWidthStr::width(self.text.as_str())
    }
}

/// Rich text widget with multiple styled spans
pub struct RichText {
    /// Spans
    spans: Vec<Span>,
    /// Default style for unstyled text
    default_style: Style,
    /// Widget props for CSS integration
    props: WidgetProps,
}

impl RichText {
    /// Create a new empty rich text
    pub fn new() -> Self {
        Self {
            spans: Vec::new(),
            default_style: Style::default(),
            props: WidgetProps::new(),
        }
    }

    /// Create from a plain string
    pub fn plain(text: impl Into<String>) -> Self {
        Self::new().push(text, Style::default())
    }

    /// Create from markup string
    ///
    /// Supported tags:
    /// - `[bold]`, `[b]` - Bold text
    /// - `[italic]`, `[i]` - Italic text
    /// - `[underline]`, `[u]` - Underlined text
    /// - `[dim]` - Dimmed text
    /// - `[strike]`, `[s]` - Strikethrough
    /// - `[red]`, `[green]`, `[blue]`, `[yellow]`, `[cyan]`, `[magenta]`, `[white]` - Colors
    /// - `[link=URL]` - Hyperlink
    /// - `[/]` - Reset to default
    ///
    /// Tags can be combined: `[bold red]text[/]`
    pub fn markup(text: &str) -> Self {
        let mut rich = Self::new();
        rich.parse_markup(text);
        rich
    }

    /// Push a styled span
    pub fn push(mut self, text: impl Into<String>, style: Style) -> Self {
        self.spans.push(Span::styled(text, style));
        self
    }

    /// Push a plain text span
    pub fn text(mut self, text: impl Into<String>) -> Self {
        self.spans.push(Span::new(text));
        self
    }

    /// Push a hyperlink span
    pub fn push_link(mut self, text: impl Into<String>, url: impl Into<String>) -> Self {
        self.spans.push(Span::link(text, url));
        self
    }

    /// Push a span
    pub fn span(mut self, span: Span) -> Self {
        self.spans.push(span);
        self
    }

    /// Set default style
    pub fn default_style(mut self, style: Style) -> Self {
        self.default_style = style;
        self
    }

    /// Append styled text (mutable version)
    pub fn append(&mut self, text: impl Into<String>, style: Style) {
        self.spans.push(Span::styled(text, style));
    }

    /// Append a hyperlink (mutable version)
    pub fn append_link(&mut self, text: impl Into<String>, url: impl Into<String>) {
        self.spans.push(Span::link(text, url));
    }

    /// Get total width
    pub fn width(&self) -> usize {
        self.spans.iter().map(|s| s.width()).sum()
    }

    /// Get span count
    pub fn len(&self) -> usize {
        self.spans.len()
    }

    /// Check if empty
    pub fn is_empty(&self) -> bool {
        self.spans.is_empty()
    }

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

    /// Parse markup string
    fn parse_markup(&mut self, text: &str) {
        let mut current_style = Style::default();
        let mut current_link: Option<String> = None;
        let mut buffer = String::new();
        let mut chars = text.chars().peekable();

        while let Some(ch) = chars.next() {
            if ch == '[' {
                // Flush buffer with current style
                if !buffer.is_empty() {
                    let mut span = Span::styled(buffer.clone(), current_style.clone());
                    if let Some(ref url) = current_link {
                        span.link = Some(url.clone());
                    }
                    self.spans.push(span);
                    buffer.clear();
                }

                // Parse tag
                let mut tag = String::new();
                for c in chars.by_ref() {
                    if c == ']' {
                        break;
                    }
                    tag.push(c);
                }

                // Handle reset tag
                if tag == "/" {
                    current_style = Style::default();
                    current_link = None;
                    continue;
                }

                // Parse tag attributes
                for part in tag.split_whitespace() {
                    if let Some(link) = part.strip_prefix("link=") {
                        current_link = Some(link.to_string());
                        current_style.underline = true;
                        if current_style.fg.is_none() {
                            current_style.fg = Some(Color::CYAN);
                        }
                    } else {
                        match part.to_lowercase().as_str() {
                            "bold" | "b" => current_style.bold = true,
                            "italic" | "i" => current_style.italic = true,
                            "underline" | "u" => current_style.underline = true,
                            "dim" => current_style.dim = true,
                            "strike" | "s" => current_style.strikethrough = true,
                            "reverse" | "rev" => current_style.reverse = true,
                            "red" => current_style.fg = Some(Color::RED),
                            "green" => current_style.fg = Some(Color::GREEN),
                            "blue" => current_style.fg = Some(Color::BLUE),
                            "yellow" => current_style.fg = Some(Color::YELLOW),
                            "cyan" => current_style.fg = Some(Color::CYAN),
                            "magenta" => current_style.fg = Some(Color::MAGENTA),
                            "white" => current_style.fg = Some(Color::WHITE),
                            "black" => current_style.fg = Some(Color::BLACK),
                            // Background colors with "on_" prefix
                            "on_red" => current_style.bg = Some(Color::RED),
                            "on_green" => current_style.bg = Some(Color::GREEN),
                            "on_blue" => current_style.bg = Some(Color::BLUE),
                            "on_yellow" => current_style.bg = Some(Color::YELLOW),
                            "on_cyan" => current_style.bg = Some(Color::CYAN),
                            "on_magenta" => current_style.bg = Some(Color::MAGENTA),
                            "on_white" => current_style.bg = Some(Color::WHITE),
                            "on_black" => current_style.bg = Some(Color::BLACK),
                            _ => {}
                        }
                    }
                }
            } else {
                buffer.push(ch);
            }
        }

        // Flush remaining buffer
        if !buffer.is_empty() {
            let mut span = Span::styled(buffer, current_style);
            if let Some(url) = current_link {
                span.link = Some(url);
            }
            self.spans.push(span);
        }
    }
}

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

impl View for RichText {
    crate::impl_view_meta!("RichText");

    fn render(&self, ctx: &mut RenderContext) {
        let area = ctx.area;
        if area.width == 0 || area.height == 0 {
            return;
        }

        let mut x: u16 = 0;

        for span in &self.spans {
            // Register hyperlink if present
            let hyperlink_id = span
                .link
                .as_ref()
                .map(|url| ctx.buffer.register_hyperlink(url));

            let modifier = span.style.to_modifier();

            for ch in span.text.chars() {
                if x >= area.width {
                    break;
                }

                let char_width = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1) as u16;

                let mut cell = Cell::new(ch);
                cell.fg = span.style.fg;
                cell.bg = span.style.bg;
                cell.modifier = modifier;
                cell.hyperlink_id = hyperlink_id;

                ctx.set(x, 0, cell);

                // Handle wide characters
                if char_width == 2 && x + 1 < area.width {
                    let mut cont = Cell::continuation();
                    cont.bg = span.style.bg;
                    cont.hyperlink_id = hyperlink_id;
                    ctx.set(x + 1, 0, cont);
                }

                x += char_width;
            }
        }
    }
}

impl_styled_view!(RichText);
impl_props_builders!(RichText);

// ─────────────────────────────────────────────────────────────────────────────
// Helper functions
// ─────────────────────────────────────────────────────────────────────────────

/// Create a new rich text
pub fn rich_text() -> RichText {
    RichText::new()
}

/// Create rich text from markup
pub fn markup(text: &str) -> RichText {
    RichText::markup(text)
}

/// Create a styled span
pub fn span(text: impl Into<String>) -> Span {
    Span::new(text)
}

/// Create a style
pub fn style() -> Style {
    Style::new()
}