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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
//! A component for displaying usage metrics.
//!
//! [`UsageDisplay`] provides a display of usage metrics such as CPU, memory,
//! disk, or any arbitrary label-value pair. Metrics can be arranged in
//! horizontal, vertical, or grid layouts with optional borders and icons.
//!
//! This is a **display-only** component that does not receive keyboard focus.
//! State is stored in [`UsageDisplayState`] and updated via
//! [`UsageDisplayMessage`].
//!
//! # Layouts
//!
//! - [`UsageLayout::Horizontal`]: Compact inline format with separator
//! - [`UsageLayout::Vertical`]: Bordered one-per-line display
//! - [`UsageLayout::Grid`]: Bordered N-column grid layout
//!
//! # Example
//!
//! ```rust
//! use envision::component::{
//!     UsageDisplay, UsageDisplayMessage, UsageDisplayState, UsageLayout, UsageMetric, Component,
//! };
//! use ratatui::style::Color;
//!
//! let state = UsageDisplayState::new()
//!     .metric(UsageMetric::new("CPU", "45%").with_color(Color::Green))
//!     .metric(UsageMetric::new("Memory", "3.2 GB").with_color(Color::Yellow))
//!     .metric(UsageMetric::new("Disk", "120 GB").with_color(Color::Cyan));
//!
//! assert_eq!(state.len(), 3);
//! ```

mod state;

use ratatui::prelude::*;
use ratatui::widgets::{Block, Borders, Paragraph};

use super::{Component, RenderContext};
use crate::theme::Theme;

/// Layout style for usage metrics display.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub enum UsageLayout {
    /// Metrics displayed inline with a separator: `"CPU: 45% | Memory: 3.2 GB"`.
    #[default]
    Horizontal,
    /// Bordered, one metric per line.
    Vertical,
    /// Bordered grid with the given number of columns.
    Grid(usize),
}

/// A single usage metric entry.
///
/// Represents a label-value pair with optional color and icon.
///
/// # Example
///
/// ```rust
/// use envision::component::UsageMetric;
/// use ratatui::style::Color;
///
/// let metric = UsageMetric::new("CPU", "45%")
///     .with_color(Color::Green)
///     .with_icon("*");
///
/// assert_eq!(metric.label(), "CPU");
/// assert_eq!(metric.value(), "45%");
/// assert_eq!(metric.color(), Some(Color::Green));
/// assert_eq!(metric.icon(), Some("*"));
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct UsageMetric {
    /// The metric label (e.g., "CPU", "Memory").
    label: String,
    /// The metric value (e.g., "45%", "3.2 GB").
    value: String,
    /// Optional color for the value.
    color: Option<Color>,
    /// Optional icon prefix.
    icon: Option<String>,
}

impl UsageMetric {
    /// Creates a new usage metric with a label and value.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::UsageMetric;
    ///
    /// let metric = UsageMetric::new("CPU", "45%");
    /// assert_eq!(metric.label(), "CPU");
    /// assert_eq!(metric.value(), "45%");
    /// assert_eq!(metric.color(), None);
    /// assert_eq!(metric.icon(), None);
    /// ```
    pub fn new(label: impl Into<String>, value: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            value: value.into(),
            color: None,
            icon: None,
        }
    }

    /// Sets the color for the metric value.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::UsageMetric;
    /// use ratatui::style::Color;
    ///
    /// let metric = UsageMetric::new("CPU", "45%").with_color(Color::Green);
    /// assert_eq!(metric.color(), Some(Color::Green));
    /// ```
    pub fn with_color(mut self, color: Color) -> Self {
        self.color = Some(color);
        self
    }

    /// Sets the icon prefix for the metric.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::UsageMetric;
    ///
    /// let metric = UsageMetric::new("CPU", "45%").with_icon("*");
    /// assert_eq!(metric.icon(), Some("*"));
    /// ```
    pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
        self.icon = Some(icon.into());
        self
    }

    /// Returns the metric label.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::UsageMetric;
    ///
    /// let metric = UsageMetric::new("CPU", "45%");
    /// assert_eq!(metric.label(), "CPU");
    /// ```
    pub fn label(&self) -> &str {
        &self.label
    }

    /// Returns the metric value.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::UsageMetric;
    ///
    /// let metric = UsageMetric::new("CPU", "45%");
    /// assert_eq!(metric.value(), "45%");
    /// ```
    pub fn value(&self) -> &str {
        &self.value
    }

    /// Returns the optional color.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::UsageMetric;
    /// use ratatui::style::Color;
    ///
    /// let metric = UsageMetric::new("CPU", "45%").with_color(Color::Green);
    /// assert_eq!(metric.color(), Some(Color::Green));
    /// ```
    pub fn color(&self) -> Option<Color> {
        self.color
    }

    /// Returns the optional icon.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::UsageMetric;
    ///
    /// let metric = UsageMetric::new("CPU", "45%").with_icon("*");
    /// assert_eq!(metric.icon(), Some("*"));
    /// ```
    pub fn icon(&self) -> Option<&str> {
        self.icon.as_deref()
    }

    /// Sets the metric label.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::UsageMetric;
    ///
    /// let mut metric = UsageMetric::new("CPU", "45%");
    /// metric.set_label("Processor");
    /// assert_eq!(metric.label(), "Processor");
    /// ```
    pub fn set_label(&mut self, label: impl Into<String>) {
        self.label = label.into();
    }

    /// Sets the metric value.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::UsageMetric;
    ///
    /// let mut metric = UsageMetric::new("CPU", "45%");
    /// metric.set_value("80%");
    /// assert_eq!(metric.value(), "80%");
    /// ```
    pub fn set_value(&mut self, value: impl Into<String>) {
        self.value = value.into();
    }

    /// Sets the optional color.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::UsageMetric;
    /// use ratatui::style::Color;
    ///
    /// let mut metric = UsageMetric::new("CPU", "45%");
    /// metric.set_color(Some(Color::Red));
    /// assert_eq!(metric.color(), Some(Color::Red));
    /// ```
    pub fn set_color(&mut self, color: Option<Color>) {
        self.color = color;
    }

    /// Sets the optional icon.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::UsageMetric;
    ///
    /// let mut metric = UsageMetric::new("CPU", "45%");
    /// metric.set_icon(Some("*".to_string()));
    /// assert_eq!(metric.icon(), Some("*"));
    /// ```
    pub fn set_icon(&mut self, icon: Option<String>) {
        self.icon = icon;
    }
}

/// Messages that can be sent to a UsageDisplay component.
#[derive(Clone, Debug, PartialEq)]
pub enum UsageDisplayMessage {
    /// Set all metrics at once.
    SetMetrics(Vec<UsageMetric>),
    /// Add a single metric.
    AddMetric(UsageMetric),
    /// Remove a metric by label.
    RemoveMetric(String),
    /// Update a metric's value by label.
    UpdateValue {
        /// The label of the metric to update.
        label: String,
        /// The new value.
        value: String,
    },
    /// Update a metric's color by label.
    UpdateColor {
        /// The label of the metric to update.
        label: String,
        /// The new color (None to clear).
        color: Option<Color>,
    },
    /// Set the layout style.
    SetLayout(UsageLayout),
    /// Set the title.
    SetTitle(Option<String>),
    /// Set the separator used in horizontal layout.
    SetSeparator(String),
    /// Clear all metrics.
    Clear,
}

/// State for a UsageDisplay component.
///
/// Contains all metrics and display configuration.
///
/// # Example
///
/// ```rust
/// use envision::component::{UsageDisplayState, UsageLayout, UsageMetric};
///
/// let state = UsageDisplayState::new()
///     .with_layout(UsageLayout::Vertical)
///     .with_title("System")
///     .metric(UsageMetric::new("CPU", "45%"))
///     .metric(UsageMetric::new("Memory", "3.2 GB"));
///
/// assert_eq!(state.len(), 2);
/// assert_eq!(state.layout(), UsageLayout::Vertical);
/// assert_eq!(state.title(), Some("System"));
/// ```
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct UsageDisplayState {
    /// All usage metrics.
    metrics: Vec<UsageMetric>,
    /// Layout style.
    layout: UsageLayout,
    /// Optional title for bordered layouts.
    title: Option<String>,
    /// Separator for horizontal layout.
    separator: String,
    /// Whether the component is disabled.
    disabled: bool,
}

impl Default for UsageDisplayState {
    fn default() -> Self {
        Self {
            metrics: Vec::new(),
            layout: UsageLayout::default(),
            title: None,
            separator: " \u{2502} ".to_string(), // " | " (thin vertical box char)
            disabled: false,
        }
    }
}

/// A component for displaying usage metrics.
///
/// `UsageDisplay` renders a collection of label-value metrics in various
/// layouts. This is a display-only component; it does not receive focus.
///
/// # Layouts
///
/// **Horizontal** (compact, no borders):
/// ```text
/// CPU: 45% | Memory: 3.2 GB | Disk: 120 GB
/// ```
///
/// **Vertical** (bordered, one per line):
/// ```text
/// +-- System --------+
/// | CPU: 45%         |
/// | Memory: 3.2 GB   |
/// | Disk: 120 GB     |
/// +------------------+
/// ```
///
/// **Grid(2)** (bordered, 2 columns):
/// ```text
/// +-- System ---------+
/// | CPU: 45%  | Mem: 3.2 GB |
/// | Disk: 120 |             |
/// +---------------------------+
/// ```
///
/// # Example
///
/// ```rust
/// use envision::component::{
///     UsageDisplay, UsageDisplayMessage, UsageDisplayState, UsageMetric, Component,
/// };
///
/// let mut state = UsageDisplayState::new()
///     .metric(UsageMetric::new("CPU", "45%"))
///     .metric(UsageMetric::new("Memory", "3.2 GB"));
///
/// // Update a metric value
/// UsageDisplay::update(
///     &mut state,
///     UsageDisplayMessage::UpdateValue {
///         label: "CPU".to_string(),
///         value: "80%".to_string(),
///     },
/// );
///
/// assert_eq!(state.find("CPU").unwrap().value(), "80%");
/// ```
pub struct UsageDisplay;

impl UsageDisplay {
    /// Renders a single metric as a sequence of spans.
    fn metric_spans(metric: &UsageMetric, theme: &Theme) -> Vec<Span<'static>> {
        let mut spans = Vec::new();

        if let Some(icon) = &metric.icon {
            spans.push(Span::styled(format!("{} ", icon), theme.normal_style()));
        }

        spans.push(Span::styled(
            format!("{}: ", metric.label),
            theme.normal_style(),
        ));

        let value_style = if let Some(color) = metric.color {
            Style::default().fg(color)
        } else {
            theme.normal_style()
        };
        spans.push(Span::styled(metric.value.clone(), value_style));

        spans
    }

    /// Renders horizontal layout.
    fn view_horizontal(state: &UsageDisplayState, frame: &mut Frame, area: Rect, theme: &Theme) {
        let mut spans = Vec::new();
        for (i, metric) in state.metrics.iter().enumerate() {
            if i > 0 {
                spans.push(Span::styled(
                    state.separator.clone(),
                    theme.disabled_style(),
                ));
            }
            spans.extend(Self::metric_spans(metric, theme));
        }

        let line = Line::from(spans);
        let paragraph = Paragraph::new(line);

        let annotation = crate::annotation::Annotation::new(crate::annotation::WidgetType::Custom(
            "UsageDisplay".to_string(),
        ))
        .with_id("usage_display")
        .with_meta("metric_count", state.metrics.len().to_string())
        .with_meta("layout", "horizontal".to_string());
        let annotated = crate::annotation::Annotate::new(paragraph, annotation);
        frame.render_widget(annotated, area);
    }

    /// Renders vertical layout.
    fn view_vertical(state: &UsageDisplayState, frame: &mut Frame, area: Rect, theme: &Theme) {
        let mut block = Block::default().borders(Borders::ALL);
        if let Some(title) = &state.title {
            block = block.title(format!(" {} ", title));
        }
        let inner = block.inner(area);
        frame.render_widget(block, area);

        let lines: Vec<Line<'static>> = state
            .metrics
            .iter()
            .map(|metric| Line::from(Self::metric_spans(metric, theme)))
            .collect();

        let paragraph = Paragraph::new(lines);

        let annotation = crate::annotation::Annotation::new(crate::annotation::WidgetType::Custom(
            "UsageDisplay".to_string(),
        ))
        .with_id("usage_display")
        .with_meta("metric_count", state.metrics.len().to_string())
        .with_meta("layout", "vertical".to_string());
        let annotated = crate::annotation::Annotate::new(paragraph, annotation);
        frame.render_widget(annotated, inner);
    }

    /// Renders grid layout.
    fn view_grid(
        state: &UsageDisplayState,
        frame: &mut Frame,
        area: Rect,
        theme: &Theme,
        columns: usize,
    ) {
        let columns = columns.max(1);

        let mut block = Block::default().borders(Borders::ALL);
        if let Some(title) = &state.title {
            block = block.title(format!(" {} ", title));
        }
        let inner = block.inner(area);
        frame.render_widget(block, area);

        if state.metrics.is_empty() || inner.width == 0 || inner.height == 0 {
            return;
        }

        let col_width = inner.width / columns as u16;
        if col_width == 0 {
            return;
        }

        let rows: Vec<&[UsageMetric]> = state.metrics.chunks(columns).collect();

        let mut lines: Vec<Line<'static>> = Vec::new();
        for row in &rows {
            let mut spans: Vec<Span<'static>> = Vec::new();
            for (col_idx, metric) in row.iter().enumerate() {
                let metric_spans = Self::metric_spans(metric, theme);
                let metric_text_len: usize = metric_spans.iter().map(|s| s.content.len()).sum();
                spans.extend(metric_spans);

                // Pad to column width for all but last column
                if col_idx < columns - 1 {
                    let padding = (col_width as usize).saturating_sub(metric_text_len);
                    if padding > 0 {
                        spans.push(Span::raw(" ".repeat(padding)));
                    }
                }
            }
            lines.push(Line::from(spans));
        }

        let paragraph = Paragraph::new(lines);

        let annotation = crate::annotation::Annotation::new(crate::annotation::WidgetType::Custom(
            "UsageDisplay".to_string(),
        ))
        .with_id("usage_display")
        .with_meta("metric_count", state.metrics.len().to_string())
        .with_meta("layout", format!("grid({})", columns));
        let annotated = crate::annotation::Annotate::new(paragraph, annotation);
        frame.render_widget(annotated, inner);
    }
}

impl Component for UsageDisplay {
    type State = UsageDisplayState;
    type Message = UsageDisplayMessage;
    type Output = ();

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

    fn update(state: &mut Self::State, msg: Self::Message) -> Option<Self::Output> {
        match msg {
            UsageDisplayMessage::SetMetrics(metrics) => {
                state.metrics = metrics;
            }
            UsageDisplayMessage::AddMetric(metric) => {
                state.metrics.push(metric);
            }
            UsageDisplayMessage::RemoveMetric(label) => {
                state.metrics.retain(|m| m.label != label);
            }
            UsageDisplayMessage::UpdateValue { label, value } => {
                if let Some(metric) = state.metrics.iter_mut().find(|m| m.label == label) {
                    metric.value = value;
                }
            }
            UsageDisplayMessage::UpdateColor { label, color } => {
                if let Some(metric) = state.metrics.iter_mut().find(|m| m.label == label) {
                    metric.color = color;
                }
            }
            UsageDisplayMessage::SetLayout(layout) => {
                state.layout = layout;
            }
            UsageDisplayMessage::SetTitle(title) => {
                state.title = title;
            }
            UsageDisplayMessage::SetSeparator(separator) => {
                state.separator = separator;
            }
            UsageDisplayMessage::Clear => {
                state.metrics.clear();
            }
        }
        None // Display-only, no output
    }

    fn view(state: &Self::State, ctx: &mut RenderContext<'_, '_>) {
        if state.metrics.is_empty() || ctx.area.width == 0 || ctx.area.height == 0 {
            return;
        }

        match state.layout {
            UsageLayout::Horizontal => Self::view_horizontal(state, ctx.frame, ctx.area, ctx.theme),
            UsageLayout::Vertical => Self::view_vertical(state, ctx.frame, ctx.area, ctx.theme),
            UsageLayout::Grid(cols) => Self::view_grid(state, ctx.frame, ctx.area, ctx.theme, cols),
        }
    }
}

#[cfg(test)]
mod tests;