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
//! A large pixel text component for dashboard hero numbers and KPI values.
//!
//! [`BigText`] renders text using large block characters where each character
//! occupies 3 rows and a variable width. This is ideal for dashboard counters,
//! clocks, and key performance indicators that need to stand out visually.
//!
//! State is stored in [`BigTextState`] and updated via [`BigTextMessage`].
//!
//! # Example
//!
//! ```rust
//! use envision::component::{Component, BigText, BigTextState, BigTextMessage};
//! use ratatui::prelude::*;
//!
//! let state = BigTextState::new("12:30")
//!     .with_color(Color::Cyan)
//!     .with_alignment(Alignment::Center);
//!
//! assert_eq!(state.text(), "12:30");
//! assert_eq!(state.color(), Some(Color::Cyan));
//! assert_eq!(state.alignment(), Alignment::Center);
//! ```

use ratatui::prelude::*;
use ratatui::widgets::Paragraph;

use super::{Component, EventContext, RenderContext};

/// Returns the 3-row block representation of a character.
///
/// Each supported character is rendered as an array of 3 string slices,
/// one per row. All rows for a given character have the same display width.
///
/// # Supported characters
///
/// - Digits: `0`-`9`
/// - Punctuation: `.`, `:`, `-`, `/`, `%`, ` `
/// - Uppercase letters: `A`-`Z`
///
/// Unsupported characters return a `?` placeholder glyph.
///
/// # Example
///
/// ```rust
/// use envision::component::big_char;
///
/// let rows = big_char('0');
/// assert_eq!(rows.len(), 3);
/// assert_eq!(rows[0], "█▀█");
/// assert_eq!(rows[1], "█ █");
/// assert_eq!(rows[2], "▀▀▀");
/// ```
pub fn big_char(ch: char) -> [&'static str; 3] {
    match ch {
        '0' => ["█▀█", "█ █", "▀▀▀"],
        '1' => ["▀█ ", "", "▀▀▀"],
        '2' => ["▀▀█", "█▀▀", "▀▀▀"],
        '3' => ["▀▀█", " ▀█", "▀▀▀"],
        '4' => ["█ █", "▀▀█", ""],
        '5' => ["█▀▀", "▀▀█", "▀▀▀"],
        '6' => ["█▀▀", "█▀█", "▀▀▀"],
        '7' => ["▀▀█", "", ""],
        '8' => ["█▀█", "█▀█", "▀▀▀"],
        '9' => ["█▀█", "▀▀█", "▀▀▀"],
        '.' => [" ", "", " "],
        ':' => ["", " ", ""],
        '-' => ["   ", "▀▀▀", "   "],
        '/' => ["", "", ""],
        '%' => ["█ █", "", "█ █"],
        ' ' => ["   ", "   ", "   "],

        'A' => ["█▀█", "█▀█", "▀ ▀"],
        'B' => ["█▀▄", "█▀█", "▀▀▀"],
        'C' => ["█▀▀", "", "▀▀▀"],
        'D' => ["█▀▄", "█ █", "▀▀▀"],
        'E' => ["█▀▀", "█▀▀", "▀▀▀"],
        'F' => ["█▀▀", "█▀ ", ""],
        'G' => ["█▀▀", "█▀█", "▀▀▀"],
        'H' => ["█ █", "█▀█", "▀ ▀"],
        'I' => ["▀█▀", "", "▀▀▀"],
        'J' => ["", "", "▀▀▀"],
        'K' => ["█ █", "█▀▄", "▀ ▀"],
        'L' => ["", "", "▀▀▀"],
        'M' => ["█▄█", "█ █", "▀ ▀"],
        'N' => ["█▀█", "█ █", "▀ ▀"],
        'O' => ["█▀█", "█ █", "▀▀▀"],
        'P' => ["█▀█", "█▀▀", ""],
        'Q' => ["█▀█", "█▄█", "▀▀▀"],
        'R' => ["█▀█", "█▀▄", "▀ ▀"],
        'S' => ["█▀▀", "▀▀█", "▀▀▀"],
        'T' => ["▀█▀", "", ""],
        'U' => ["█ █", "█ █", "▀▀▀"],
        'V' => ["█ █", "█ █", ""],
        'W' => ["█ █", "█ █", "▀▄▀"],
        'X' => ["█ █", "", "█ █"],
        'Y' => ["█ █", "", ""],
        'Z' => ["▀▀█", "", "▀▀▀"],

        _ => ["▀▀▀", "", ""],
    }
}

/// Returns the display width of a big character glyph.
///
/// This measures the Unicode display width of the first row of the
/// character's 3-row representation.
///
/// # Example
///
/// ```rust
/// use envision::component::big_char_width;
///
/// assert_eq!(big_char_width('0'), 3);
/// assert_eq!(big_char_width('.'), 1);
/// assert_eq!(big_char_width(':'), 1);
/// ```
pub fn big_char_width(ch: char) -> usize {
    unicode_width::UnicodeWidthStr::width(big_char(ch)[0])
}

/// Messages that can be sent to a BigText component.
#[derive(Clone, Debug, PartialEq)]
pub enum BigTextMessage {
    /// Replace the displayed text.
    SetText(String),
    /// Set the color override.
    SetColor(Option<Color>),
    /// Set the text alignment.
    SetAlignment(Alignment),
}

/// State for a BigText component.
///
/// Contains the text to display in large block characters, along with
/// optional color and alignment configuration.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct BigTextState {
    /// The text to render in large block characters.
    text: String,
    /// Optional color override for the text.
    color: Option<Color>,
    /// Text alignment within the render area.
    #[cfg_attr(feature = "serialization", serde(skip))]
    alignment: Alignment,
}

impl Default for BigTextState {
    fn default() -> Self {
        Self {
            text: String::new(),
            color: None,
            alignment: Alignment::Center,
        }
    }
}

impl BigTextState {
    /// Creates a new BigText state with the given text.
    ///
    /// The default alignment is center and no color override is applied.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::BigTextState;
    ///
    /// let state = BigTextState::new("42");
    /// assert_eq!(state.text(), "42");
    /// assert_eq!(state.color(), None);
    /// ```
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            ..Self::default()
        }
    }

    // ---- Builders ----

    /// Sets the color override (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::BigTextState;
    /// use ratatui::style::Color;
    ///
    /// let state = BigTextState::new("99")
    ///     .with_color(Color::Green);
    /// assert_eq!(state.color(), Some(Color::Green));
    /// ```
    pub fn with_color(mut self, color: Color) -> Self {
        self.color = Some(color);
        self
    }

    /// Sets the text alignment (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::BigTextState;
    /// use ratatui::prelude::Alignment;
    ///
    /// let state = BigTextState::new("OK")
    ///     .with_alignment(Alignment::Left);
    /// assert_eq!(state.alignment(), Alignment::Left);
    /// ```
    pub fn with_alignment(mut self, alignment: Alignment) -> Self {
        self.alignment = alignment;
        self
    }

    // ---- Getters ----

    /// Returns the text being displayed.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::BigTextState;
    ///
    /// let state = BigTextState::new("123");
    /// assert_eq!(state.text(), "123");
    /// ```
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Returns the optional color override.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::BigTextState;
    ///
    /// let state = BigTextState::new("0");
    /// assert_eq!(state.color(), None);
    /// ```
    pub fn color(&self) -> Option<Color> {
        self.color
    }

    /// Returns the text alignment.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::BigTextState;
    /// use ratatui::prelude::Alignment;
    ///
    /// let state = BigTextState::new("0");
    /// assert_eq!(state.alignment(), Alignment::Center);
    /// ```
    pub fn alignment(&self) -> Alignment {
        self.alignment
    }

    // ---- Setters ----

    /// Sets the text to display.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::BigTextState;
    ///
    /// let mut state = BigTextState::new("old");
    /// state.set_text("new");
    /// assert_eq!(state.text(), "new");
    /// ```
    pub fn set_text(&mut self, text: impl Into<String>) {
        self.text = text.into();
    }

    /// Sets the color override.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::BigTextState;
    /// use ratatui::style::Color;
    ///
    /// let mut state = BigTextState::new("0");
    /// state.set_color(Some(Color::Red));
    /// assert_eq!(state.color(), Some(Color::Red));
    /// ```
    pub fn set_color(&mut self, color: Option<Color>) {
        self.color = color;
    }

    /// Sets the text alignment.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::BigTextState;
    /// use ratatui::prelude::Alignment;
    ///
    /// let mut state = BigTextState::new("0");
    /// state.set_alignment(Alignment::Right);
    /// assert_eq!(state.alignment(), Alignment::Right);
    /// ```
    pub fn set_alignment(&mut self, alignment: Alignment) {
        self.alignment = alignment;
    }

    // ---- Instance methods ----

    /// Maps an input event to a message (instance method).
    ///
    /// BigText is display-only, so this always returns `None`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::BigTextState;
    /// use envision::input::{Event, Key};
    ///
    /// let state = BigTextState::new("42");
    /// assert_eq!(state.handle_event(&Event::key(Key::Enter)), None);
    /// ```
    pub fn handle_event(&self, event: &crate::input::Event) -> Option<BigTextMessage> {
        BigText::handle_event(self, event, &EventContext::default())
    }

    /// Updates the state with a message, returning any output (instance method).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::BigTextState;
    /// use envision::component::BigTextMessage;
    ///
    /// let mut state = BigTextState::new("old");
    /// state.update(BigTextMessage::SetText("new".to_string()));
    /// assert_eq!(state.text(), "new");
    /// ```
    pub fn update(&mut self, msg: BigTextMessage) -> Option<()> {
        BigText::update(self, msg)
    }

    /// Dispatches an event by mapping and updating (instance method).
    ///
    /// BigText is display-only, so this always returns `None`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::BigTextState;
    /// use envision::input::{Event, Key};
    ///
    /// let mut state = BigTextState::new("42");
    /// assert_eq!(state.dispatch_event(&Event::key(Key::Enter)), None);
    /// ```
    pub fn dispatch_event(&mut self, event: &crate::input::Event) -> Option<()> {
        BigText::dispatch_event(self, event, &EventContext::default())
    }
}

/// Builds the rendered content for one row of big text.
///
/// Given a text string and a row index (0-2), this concatenates the
/// appropriate row slice from each character's big font glyph, with a
/// single space separator between characters.
fn build_row(text: &str, row: usize) -> String {
    let mut result = String::new();
    let chars: Vec<char> = text.chars().collect();
    for (i, &ch) in chars.iter().enumerate() {
        if i > 0 {
            result.push(' ');
        }
        let glyph = big_char(ch.to_ascii_uppercase());
        result.push_str(glyph[row]);
    }
    result
}

/// A large pixel text component for dashboard hero numbers and KPI values.
///
/// Renders text using large 3-row block characters. This is a display-only
/// component and does not handle interactive events.
///
/// # Example
///
/// ```rust
/// use envision::component::{Component, BigText, BigTextState};
/// use ratatui::prelude::*;
///
/// let state = BigTextState::new("99.9%")
///     .with_color(Color::Green)
///     .with_alignment(Alignment::Center);
///
/// assert_eq!(state.text(), "99.9%");
/// ```
pub struct BigText;

impl Component for BigText {
    type State = BigTextState;
    type Message = BigTextMessage;
    type Output = ();

    fn init() -> Self::State {
        BigTextState::default()
    }

    fn update(state: &mut Self::State, msg: Self::Message) -> Option<Self::Output> {
        match msg {
            BigTextMessage::SetText(text) => state.text = text,
            BigTextMessage::SetColor(color) => state.color = color,
            BigTextMessage::SetAlignment(alignment) => state.alignment = alignment,
        }
        None
    }

    fn view(state: &Self::State, ctx: &mut RenderContext<'_, '_>) {
        crate::annotation::with_registry(|reg| {
            reg.register(
                ctx.area,
                crate::annotation::Annotation::big_text("big_text")
                    .with_label(&state.text)
                    .with_disabled(ctx.disabled),
            );
        });

        if ctx.area.height == 0 || ctx.area.width == 0 {
            return;
        }

        let style = if ctx.disabled {
            ctx.theme.disabled_style()
        } else if let Some(color) = state.color {
            Style::default().fg(color)
        } else {
            ctx.theme.normal_style()
        };

        // Build the 3 rows of big text
        let lines: Vec<Line<'_>> = (0..3)
            .map(|row| {
                let row_text = build_row(&state.text, row);
                Line::from(Span::styled(row_text, style))
            })
            .collect();

        // Vertically center within the available ctx.area
        let content_height: u16 = 3;
        let vertical_offset = ctx.area.height.saturating_sub(content_height) / 2;

        let render_area = Rect::new(
            ctx.area.x,
            ctx.area.y + vertical_offset,
            ctx.area.width,
            content_height.min(ctx.area.height.saturating_sub(vertical_offset)),
        );

        if render_area.height > 0 {
            let paragraph = Paragraph::new(lines).alignment(state.alignment);
            ctx.frame.render_widget(paragraph, render_area);
        }
    }
}

#[cfg(test)]
mod tests;