envision 0.16.0

A ratatui framework for collaborative TUI development with headless testing support
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
//! Content types for rich text display.
//!
//! Provides [`StyledContent`], [`StyledBlock`], and [`StyledInline`] types
//! for building structured rich text with semantic blocks and inline styling.

use ratatui::prelude::*;
use ratatui::text::{Line as RatLine, Span as RatSpan};

use crate::theme::Theme;

/// A block-level element in styled text content.
#[derive(Clone, Debug, PartialEq)]
pub enum StyledBlock {
    /// A heading with a level (1-3).
    Heading {
        /// Heading level: 1 for top-level, 2 for secondary, 3 for tertiary.
        level: u8,
        /// The heading text.
        text: String,
    },
    /// A paragraph composed of inline elements.
    Paragraph(Vec<StyledInline>),
    /// A bulleted list where each item is a list of inline elements.
    BulletList(Vec<Vec<StyledInline>>),
    /// A numbered list where each item is a list of inline elements.
    NumberedList(Vec<Vec<StyledInline>>),
    /// A code block with optional language annotation.
    CodeBlock {
        /// Optional language for syntax highlighting hints.
        language: Option<String>,
        /// The code content.
        content: String,
    },
    /// A horizontal rule divider.
    HorizontalRule,
    /// A blank line.
    BlankLine,
    /// Raw pre-rendered lines (escape hatch for custom content).
    Raw(Vec<RatLine<'static>>),
}

/// An inline styling element within a paragraph or list item.
#[derive(Clone, Debug, PartialEq)]
pub enum StyledInline {
    /// Plain unstyled text.
    Plain(String),
    /// Bold text.
    Bold(String),
    /// Italic text.
    Italic(String),
    /// Underlined text.
    Underline(String),
    /// Strikethrough text.
    Strikethrough(String),
    /// Text with explicit foreground and/or background colors.
    Colored {
        /// The text content.
        text: String,
        /// Optional foreground color.
        fg: Option<Color>,
        /// Optional background color.
        bg: Option<Color>,
    },
    /// Inline code (displayed with distinct styling).
    Code(String),
}

/// A builder for constructing rich text content.
///
/// `StyledContent` holds a sequence of [`StyledBlock`] elements that are
/// rendered by the [`StyledText`](super::StyledText) component.
///
/// # Example
///
/// ```rust
/// use envision::component::styled_text::StyledContent;
///
/// let content = StyledContent::new()
///     .heading(1, "Welcome")
///     .text("This is a simple paragraph.")
///     .blank_line()
///     .code_block(None::<String>, "let x = 42;");
///
/// assert_eq!(content.len(), 4);
/// assert!(!content.is_empty());
/// ```
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StyledContent {
    blocks: Vec<StyledBlock>,
}

impl StyledContent {
    /// Creates an empty styled content builder.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::styled_text::StyledContent;
    ///
    /// let content = StyledContent::new();
    /// assert!(content.is_empty());
    /// assert_eq!(content.len(), 0);
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates styled content from a pre-built vector of blocks.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::styled_text::{StyledContent, StyledBlock, StyledInline};
    ///
    /// let blocks = vec![
    ///     StyledBlock::Heading { level: 1, text: "Title".to_string() },
    ///     StyledBlock::Paragraph(vec![StyledInline::Plain("Hello".to_string())]),
    /// ];
    /// let content = StyledContent::from_blocks(blocks);
    /// assert_eq!(content.len(), 2);
    /// ```
    pub fn from_blocks(blocks: Vec<StyledBlock>) -> Self {
        Self { blocks }
    }

    /// Adds a heading block.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::styled_text::StyledContent;
    ///
    /// let content = StyledContent::new()
    ///     .heading(1, "Main Title")
    ///     .heading(2, "Subtitle");
    /// assert_eq!(content.len(), 2);
    /// ```
    pub fn heading(mut self, level: u8, text: impl Into<String>) -> Self {
        self.blocks.push(StyledBlock::Heading {
            level: level.clamp(1, 3),
            text: text.into(),
        });
        self
    }

    /// Adds a paragraph composed of inline elements.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::styled_text::{StyledContent, StyledInline};
    ///
    /// let content = StyledContent::new()
    ///     .paragraph(vec![
    ///         StyledInline::Plain("Hello, ".to_string()),
    ///         StyledInline::Bold("world".to_string()),
    ///     ]);
    /// assert_eq!(content.len(), 1);
    /// ```
    pub fn paragraph(mut self, inlines: Vec<StyledInline>) -> Self {
        self.blocks.push(StyledBlock::Paragraph(inlines));
        self
    }

    /// Adds a paragraph with plain text (convenience method).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::styled_text::StyledContent;
    ///
    /// let content = StyledContent::new()
    ///     .text("Hello, world!");
    /// assert_eq!(content.len(), 1);
    /// ```
    pub fn text(self, text: impl Into<String>) -> Self {
        self.paragraph(vec![StyledInline::Plain(text.into())])
    }

    /// Adds a bulleted list.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::styled_text::{StyledContent, StyledInline};
    ///
    /// let content = StyledContent::new()
    ///     .bullet_list(vec![
    ///         vec![StyledInline::Plain("First item".to_string())],
    ///         vec![StyledInline::Plain("Second item".to_string())],
    ///     ]);
    /// assert_eq!(content.len(), 1);
    /// ```
    pub fn bullet_list(mut self, items: Vec<Vec<StyledInline>>) -> Self {
        self.blocks.push(StyledBlock::BulletList(items));
        self
    }

    /// Adds a numbered list.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::styled_text::{StyledContent, StyledInline};
    ///
    /// let content = StyledContent::new()
    ///     .numbered_list(vec![
    ///         vec![StyledInline::Plain("Step one".to_string())],
    ///         vec![StyledInline::Plain("Step two".to_string())],
    ///     ]);
    /// assert_eq!(content.len(), 1);
    /// ```
    pub fn numbered_list(mut self, items: Vec<Vec<StyledInline>>) -> Self {
        self.blocks.push(StyledBlock::NumberedList(items));
        self
    }

    /// Adds a code block with optional language annotation.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::styled_text::StyledContent;
    ///
    /// let content = StyledContent::new()
    ///     .code_block(Some("rust"), "let x = 42;");
    /// assert_eq!(content.len(), 1);
    /// ```
    pub fn code_block(
        mut self,
        language: Option<impl Into<String>>,
        content: impl Into<String>,
    ) -> Self {
        self.blocks.push(StyledBlock::CodeBlock {
            language: language.map(|l| l.into()),
            content: content.into(),
        });
        self
    }

    /// Adds a horizontal rule.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::styled_text::StyledContent;
    ///
    /// let content = StyledContent::new()
    ///     .text("Above")
    ///     .horizontal_rule()
    ///     .text("Below");
    /// assert_eq!(content.len(), 3);
    /// ```
    pub fn horizontal_rule(mut self) -> Self {
        self.blocks.push(StyledBlock::HorizontalRule);
        self
    }

    /// Adds a blank line.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::styled_text::StyledContent;
    ///
    /// let content = StyledContent::new()
    ///     .text("Paragraph 1")
    ///     .blank_line()
    ///     .text("Paragraph 2");
    /// assert_eq!(content.len(), 3);
    /// ```
    pub fn blank_line(mut self) -> Self {
        self.blocks.push(StyledBlock::BlankLine);
        self
    }

    /// Adds raw pre-rendered lines.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::styled_text::StyledContent;
    /// use ratatui::text::Line;
    ///
    /// let content = StyledContent::new()
    ///     .raw(vec![Line::from("Custom rendered line")]);
    /// assert_eq!(content.len(), 1);
    /// ```
    pub fn raw(mut self, lines: Vec<RatLine<'static>>) -> Self {
        self.blocks.push(StyledBlock::Raw(lines));
        self
    }

    /// Pushes any block element.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::styled_text::{StyledContent, StyledBlock};
    ///
    /// let content = StyledContent::new()
    ///     .push(StyledBlock::HorizontalRule)
    ///     .push(StyledBlock::BlankLine);
    /// assert_eq!(content.len(), 2);
    /// ```
    pub fn push(mut self, block: StyledBlock) -> Self {
        self.blocks.push(block);
        self
    }

    /// Returns true if there are no blocks.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::styled_text::StyledContent;
    ///
    /// assert!(StyledContent::new().is_empty());
    /// assert!(!StyledContent::new().text("hello").is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.blocks.is_empty()
    }

    /// Returns the number of blocks.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::styled_text::StyledContent;
    ///
    /// let content = StyledContent::new()
    ///     .heading(1, "Title")
    ///     .text("Body");
    /// assert_eq!(content.len(), 2);
    /// ```
    pub fn len(&self) -> usize {
        self.blocks.len()
    }

    /// Returns a reference to the blocks.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::styled_text::{StyledContent, StyledBlock};
    ///
    /// let content = StyledContent::new()
    ///     .heading(1, "Title")
    ///     .blank_line();
    /// assert_eq!(content.blocks().len(), 2);
    /// assert!(matches!(content.blocks()[1], StyledBlock::BlankLine));
    /// ```
    pub fn blocks(&self) -> &[StyledBlock] {
        &self.blocks
    }

    /// Renders this content into ratatui `Line` objects for display.
    pub(crate) fn render_lines(&self, width: u16, theme: &Theme) -> Vec<RatLine<'static>> {
        self.render_lines_styled(width, theme, theme.normal_style())
    }

    /// Renders this content using a caller-provided base style for inline text.
    ///
    /// `base_style` replaces `theme.normal_style()` for paragraphs, list item
    /// text, bold, italic, underline, strikethrough, and colored inlines.
    /// Headings, code blocks, horizontal rules, and inline code retain their
    /// semantic theme styles.
    pub(crate) fn render_lines_styled(
        &self,
        width: u16,
        theme: &Theme,
        base_style: Style,
    ) -> Vec<RatLine<'static>> {
        let mut lines = Vec::new();
        for block in &self.blocks {
            render_block(block, width, theme, base_style, &mut lines);
        }
        lines
    }
}

fn render_block(
    block: &StyledBlock,
    width: u16,
    theme: &Theme,
    base_style: Style,
    lines: &mut Vec<RatLine<'static>>,
) {
    match block {
        StyledBlock::Heading { level, text } => {
            let style = match level {
                1 => theme
                    .focused_style()
                    .add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
                2 => theme.info_style().add_modifier(Modifier::BOLD),
                _ => base_style.add_modifier(Modifier::BOLD | Modifier::ITALIC),
            };
            lines.push(RatLine::from(RatSpan::styled(text.clone(), style)));
        }
        StyledBlock::Paragraph(inlines) => {
            render_paragraph(inlines, theme, base_style, lines);
        }
        StyledBlock::BulletList(items) => {
            for item in items {
                let mut spans = vec![RatSpan::styled("", base_style)];
                for inline in item {
                    spans.push(render_inline(inline, theme, base_style));
                }
                lines.push(RatLine::from(spans));
            }
        }
        StyledBlock::NumberedList(items) => {
            for (i, item) in items.iter().enumerate() {
                let prefix = format!("  {}. ", i + 1);
                let mut spans = vec![RatSpan::styled(prefix, base_style)];
                for inline in item {
                    spans.push(render_inline(inline, theme, base_style));
                }
                lines.push(RatLine::from(spans));
            }
        }
        StyledBlock::CodeBlock { language, content } => {
            if let Some(lang) = language {
                lines.push(RatLine::from(RatSpan::styled(
                    format!("  [{}]", lang),
                    theme.disabled_style().add_modifier(Modifier::ITALIC),
                )));
            }
            for line in content.lines() {
                lines.push(RatLine::from(RatSpan::styled(
                    format!("    {}", line),
                    base_style,
                )));
            }
            // Handle empty code blocks
            if content.is_empty() {
                lines.push(RatLine::from(RatSpan::styled(
                    "    ".to_string(),
                    base_style,
                )));
            }
        }
        StyledBlock::HorizontalRule => {
            let rule = "".repeat(width as usize);
            lines.push(RatLine::from(RatSpan::styled(rule, theme.border_style())));
        }
        StyledBlock::BlankLine => {
            lines.push(RatLine::from(""));
        }
        StyledBlock::Raw(raw_lines) => {
            lines.extend(raw_lines.iter().cloned());
        }
    }
}

fn render_paragraph(
    inlines: &[StyledInline],
    theme: &Theme,
    base_style: Style,
    lines: &mut Vec<RatLine<'static>>,
) {
    let spans: Vec<RatSpan<'static>> = inlines
        .iter()
        .map(|i| render_inline(i, theme, base_style))
        .collect();
    lines.push(RatLine::from(spans));
}

fn render_inline(inline: &StyledInline, theme: &Theme, base_style: Style) -> RatSpan<'static> {
    match inline {
        // Code and Colored use theme-specific styles; everything else uses base_style
        StyledInline::Code(text) => RatSpan::styled(
            text.clone(),
            theme.info_style().add_modifier(Modifier::BOLD),
        ),
        StyledInline::Colored { text, fg, bg } => {
            let mut style = base_style;
            if let Some(fg) = fg {
                style = style.fg(*fg);
            }
            if let Some(bg) = bg {
                style = style.bg(*bg);
            }
            RatSpan::styled(text.clone(), style)
        }
        other => render_inline_styled(other, base_style),
    }
}

/// Renders an inline element using a given base style (no theme needed).
fn render_inline_styled(inline: &StyledInline, base_style: Style) -> RatSpan<'static> {
    match inline {
        StyledInline::Plain(text) => RatSpan::styled(text.clone(), base_style),
        StyledInline::Bold(text) => {
            RatSpan::styled(text.clone(), base_style.add_modifier(Modifier::BOLD))
        }
        StyledInline::Italic(text) => {
            RatSpan::styled(text.clone(), base_style.add_modifier(Modifier::ITALIC))
        }
        StyledInline::Underline(text) => {
            RatSpan::styled(text.clone(), base_style.add_modifier(Modifier::UNDERLINED))
        }
        StyledInline::Strikethrough(text) => {
            RatSpan::styled(text.clone(), base_style.add_modifier(Modifier::CROSSED_OUT))
        }
        StyledInline::Colored { text, fg, bg } => {
            let mut style = base_style;
            if let Some(fg) = fg {
                style = style.fg(*fg);
            }
            if let Some(bg) = bg {
                style = style.bg(*bg);
            }
            RatSpan::styled(text.clone(), style)
        }
        StyledInline::Code(text) => {
            RatSpan::styled(text.clone(), base_style.add_modifier(Modifier::BOLD))
        }
    }
}