envision 0.15.1

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
//! Metric widget types for the dashboard.
//!
//! Contains [`MetricKind`] and [`MetricWidget`], used by the
//! [`MetricsDashboard`](super::MetricsDashboard) component.

/// The kind of metric a widget displays.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub enum MetricKind {
    /// A numeric counter value.
    Counter {
        /// The current value.
        value: i64,
    },
    /// A gauge value with a known range.
    Gauge {
        /// The current value.
        value: u64,
        /// The maximum value.
        max: u64,
    },
    /// A status indicator (up/down).
    Status {
        /// Whether the status is "up" (healthy).
        up: bool,
    },
    /// A text-based metric.
    Text {
        /// The display text.
        text: String,
    },
}

/// A single metric widget in the dashboard.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct MetricWidget {
    /// The display label.
    pub(super) label: String,
    /// The metric kind and value.
    pub(super) kind: MetricKind,
    /// Sparkline history (recent values for trend display).
    pub(super) history: Vec<u64>,
    /// Maximum history length.
    pub(super) max_history: usize,
}

impl MetricWidget {
    /// Creates a counter widget.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MetricWidget;
    ///
    /// let widget = MetricWidget::counter("Requests", 42);
    /// assert_eq!(widget.label(), "Requests");
    /// assert_eq!(widget.display_value(), "42");
    /// ```
    pub fn counter(label: impl Into<String>, value: i64) -> Self {
        Self {
            label: label.into(),
            kind: MetricKind::Counter { value },
            history: Vec::new(),
            max_history: 20,
        }
    }

    /// Creates a gauge widget with a maximum value.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MetricWidget;
    ///
    /// let widget = MetricWidget::gauge("CPU %", 75, 100);
    /// assert_eq!(widget.display_value(), "75/100");
    /// ```
    pub fn gauge(label: impl Into<String>, value: u64, max: u64) -> Self {
        Self {
            label: label.into(),
            kind: MetricKind::Gauge { value, max },
            history: Vec::new(),
            max_history: 20,
        }
    }

    /// Creates a status indicator widget.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MetricWidget;
    ///
    /// let widget = MetricWidget::status("API", true);
    /// assert_eq!(widget.label(), "API");
    /// assert_eq!(widget.display_value(), "UP");
    /// ```
    pub fn status(label: impl Into<String>, up: bool) -> Self {
        Self {
            label: label.into(),
            kind: MetricKind::Status { up },
            history: Vec::new(),
            max_history: 0,
        }
    }

    /// Creates a text metric widget.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MetricWidget;
    ///
    /// let widget = MetricWidget::text("Version", "1.2.3");
    /// assert_eq!(widget.label(), "Version");
    /// assert_eq!(widget.display_value(), "1.2.3");
    /// ```
    pub fn text(label: impl Into<String>, text: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            kind: MetricKind::Text { text: text.into() },
            history: Vec::new(),
            max_history: 0,
        }
    }

    /// Sets the maximum history length for sparkline display (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MetricWidget;
    ///
    /// let widget = MetricWidget::counter("Ops", 0).with_max_history(50);
    /// assert_eq!(widget.history().len(), 0); // no values yet
    /// ```
    pub fn with_max_history(mut self, max: usize) -> Self {
        self.max_history = max;
        self
    }

    /// Returns the label.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MetricWidget;
    ///
    /// let widget = MetricWidget::counter("Requests", 0);
    /// assert_eq!(widget.label(), "Requests");
    /// ```
    pub fn label(&self) -> &str {
        &self.label
    }

    /// Returns the metric kind.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{MetricWidget, MetricKind};
    ///
    /// let widget = MetricWidget::status("DB", false);
    /// assert!(matches!(widget.kind(), MetricKind::Status { up: false }));
    /// ```
    pub fn kind(&self) -> &MetricKind {
        &self.kind
    }

    /// Returns the sparkline history.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MetricWidget;
    ///
    /// let widget = MetricWidget::counter("Ops", 0);
    /// assert!(widget.history().is_empty());
    /// ```
    pub fn history(&self) -> &[u64] {
        &self.history
    }

    /// Returns the display value as a string.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MetricWidget;
    ///
    /// assert_eq!(MetricWidget::counter("A", 42).display_value(), "42");
    /// assert_eq!(MetricWidget::gauge("B", 75, 100).display_value(), "75/100");
    /// assert_eq!(MetricWidget::status("C", true).display_value(), "UP");
    /// assert_eq!(MetricWidget::status("D", false).display_value(), "DOWN");
    /// assert_eq!(MetricWidget::text("E", "ok").display_value(), "ok");
    /// ```
    pub fn display_value(&self) -> String {
        match &self.kind {
            MetricKind::Counter { value } => value.to_string(),
            MetricKind::Gauge { value, max } => format!("{}/{}", value, max),
            MetricKind::Status { up } => {
                if *up {
                    "UP".to_string()
                } else {
                    "DOWN".to_string()
                }
            }
            MetricKind::Text { text } => text.clone(),
        }
    }

    /// Returns the counter value, if this is a counter widget.
    ///
    /// Returns `None` for non-counter widgets.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MetricWidget;
    ///
    /// let widget = MetricWidget::counter("Requests", 42);
    /// assert_eq!(widget.counter_value(), Some(42));
    ///
    /// let gauge = MetricWidget::gauge("Mem", 50, 100);
    /// assert_eq!(gauge.counter_value(), None);
    /// ```
    pub fn counter_value(&self) -> Option<i64> {
        if let MetricKind::Counter { value } = &self.kind {
            Some(*value)
        } else {
            None
        }
    }

    /// Returns the gauge value and max, if this is a gauge widget.
    ///
    /// Returns `None` for non-gauge widgets.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MetricWidget;
    ///
    /// let widget = MetricWidget::gauge("Memory", 512, 1024);
    /// assert_eq!(widget.gauge_value(), Some((512, 1024)));
    ///
    /// let counter = MetricWidget::counter("Ops", 0);
    /// assert_eq!(counter.gauge_value(), None);
    /// ```
    pub fn gauge_value(&self) -> Option<(u64, u64)> {
        if let MetricKind::Gauge { value, max } = &self.kind {
            Some((*value, *max))
        } else {
            None
        }
    }

    /// Returns the status (up/down), if this is a status widget.
    ///
    /// Returns `None` for non-status widgets.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MetricWidget;
    ///
    /// let widget = MetricWidget::status("API", true);
    /// assert_eq!(widget.is_status(), Some(true));
    ///
    /// let counter = MetricWidget::counter("Ops", 0);
    /// assert_eq!(counter.is_status(), None);
    /// ```
    pub fn is_status(&self) -> Option<bool> {
        if let MetricKind::Status { up } = &self.kind {
            Some(*up)
        } else {
            None
        }
    }

    /// Returns the text value, if this is a text widget.
    ///
    /// Returns `None` for non-text widgets.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MetricWidget;
    ///
    /// let widget = MetricWidget::text("Version", "1.2.3");
    /// assert_eq!(widget.text_value(), Some("1.2.3"));
    ///
    /// let counter = MetricWidget::counter("Ops", 0);
    /// assert_eq!(counter.text_value(), None);
    /// ```
    pub fn text_value(&self) -> Option<&str> {
        if let MetricKind::Text { text } = &self.kind {
            Some(text)
        } else {
            None
        }
    }

    /// Sets the counter value.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MetricWidget;
    ///
    /// let mut widget = MetricWidget::counter("Requests", 0);
    /// widget.set_counter_value(100);
    /// assert_eq!(widget.display_value(), "100");
    /// ```
    pub fn set_counter_value(&mut self, value: i64) {
        if let MetricKind::Counter { value: ref mut v } = self.kind {
            *v = value;
            if self.max_history > 0 {
                self.history.push(value.unsigned_abs());
                while self.history.len() > self.max_history {
                    self.history.remove(0);
                }
            }
        }
    }

    /// Sets the gauge value.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MetricWidget;
    ///
    /// let mut widget = MetricWidget::gauge("Memory", 0, 1024);
    /// widget.set_gauge_value(512);
    /// assert_eq!(widget.display_value(), "512/1024");
    /// ```
    pub fn set_gauge_value(&mut self, value: u64) {
        if let MetricKind::Gauge {
            value: ref mut v,
            max,
        } = self.kind
        {
            *v = value.min(max);
            if self.max_history > 0 {
                self.history.push(value);
                while self.history.len() > self.max_history {
                    self.history.remove(0);
                }
            }
        }
    }

    /// Sets the status.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MetricWidget;
    ///
    /// let mut widget = MetricWidget::status("API", true);
    /// widget.set_status(false);
    /// assert_eq!(widget.display_value(), "DOWN");
    /// ```
    pub fn set_status(&mut self, up: bool) {
        if let MetricKind::Status { up: ref mut u } = self.kind {
            *u = up;
        }
    }

    /// Sets the text value.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MetricWidget;
    ///
    /// let mut widget = MetricWidget::text("Version", "1.0");
    /// widget.set_text("2.0");
    /// assert_eq!(widget.display_value(), "2.0");
    /// ```
    pub fn set_text(&mut self, text: impl Into<String>) {
        if let MetricKind::Text { text: ref mut t } = self.kind {
            *t = text.into();
        }
    }

    /// Increments a counter by the given amount.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MetricWidget;
    ///
    /// let mut widget = MetricWidget::counter("Hits", 10);
    /// widget.increment(5);
    /// assert_eq!(widget.display_value(), "15");
    /// ```
    pub fn increment(&mut self, amount: i64) {
        if let MetricKind::Counter { ref mut value } = self.kind {
            *value += amount;
            if self.max_history > 0 {
                self.history.push(value.unsigned_abs());
                while self.history.len() > self.max_history {
                    self.history.remove(0);
                }
            }
        }
    }

    /// Returns the gauge fill percentage (0.0 to 1.0).
    ///
    /// Returns `None` for non-gauge widgets.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MetricWidget;
    ///
    /// let widget = MetricWidget::gauge("CPU", 75, 100);
    /// assert_eq!(widget.gauge_percentage(), Some(0.75));
    ///
    /// let counter = MetricWidget::counter("Ops", 10);
    /// assert_eq!(counter.gauge_percentage(), None);
    /// ```
    pub fn gauge_percentage(&self) -> Option<f64> {
        match &self.kind {
            MetricKind::Gauge { value, max } if *max > 0 => Some(*value as f64 / *max as f64),
            _ => None,
        }
    }
}