tui-lipan 0.2.0

Opinionated, component-based TUI framework for Rust - declarative components, reconciliation, layout engine, focus, overlays, and rich widgets on top of ratatui.
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
//! Chart widget.

mod layout;
mod node;
mod reconcile;

pub use layout::measure_chart;
pub use node::ChartNode;
pub use reconcile::reconcile_chart;

use std::sync::Arc;

use crate::core::element::{Element, ElementKind};
use crate::style::{BorderStyle, Length, Padding, Style};

/// Rendering mode for a chart series.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ChartSeriesMode {
    /// Draw connected trend points.
    #[default]
    Line,
    /// Draw a connected high-resolution trace using a 2x4 braille subcell grid.
    Braille,
    /// Draw vertical bars.
    Bars,
}

/// Single data series rendered on a chart.
#[derive(Clone, Debug)]
pub struct ChartSeries {
    pub(crate) name: Arc<str>,
    pub(crate) data: Arc<[f64]>,
    pub(crate) mode: ChartSeriesMode,
    pub(crate) style: Style,
    pub(crate) point_char: char,
    pub(crate) line_char: char,
    pub(crate) bar_char: char,
}

impl ChartSeries {
    /// Create a line series with a display name and numeric samples.
    pub fn new(name: impl Into<Arc<str>>, data: impl IntoIterator<Item = f64>) -> Self {
        Self {
            name: name.into(),
            data: data.into_iter().collect::<Vec<_>>().into(),
            mode: ChartSeriesMode::Line,
            style: Style::default(),
            point_char: '',
            line_char: '',
            bar_char: '',
        }
    }

    /// Set series data from a shared slice.
    pub fn data_arc(mut self, data: Arc<[f64]>) -> Self {
        self.data = data;
        self
    }

    /// Set series rendering mode.
    pub fn mode(mut self, mode: ChartSeriesMode) -> Self {
        self.mode = mode;
        self
    }

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

    /// Override the point glyph used for line mode.
    pub fn point_char(mut self, point_char: char) -> Self {
        self.point_char = point_char;
        self
    }

    /// Override the connector glyph used for line mode.
    pub fn line_char(mut self, line_char: char) -> Self {
        self.line_char = line_char;
        self
    }

    /// Override the bar glyph used for bar mode.
    pub fn bar_char(mut self, bar_char: char) -> Self {
        self.bar_char = bar_char;
        self
    }
}

/// Axis configuration.
#[derive(Clone, Debug)]
pub struct ChartAxis {
    pub(crate) show: bool,
    pub(crate) min: Option<f64>,
    pub(crate) max: Option<f64>,
    pub(crate) ticks: u16,
    pub(crate) tick_labels: Arc<[Arc<str>]>,
    pub(crate) label: Option<Arc<str>>,
    pub(crate) style: Style,
}

impl Default for ChartAxis {
    fn default() -> Self {
        Self {
            show: true,
            min: None,
            max: None,
            ticks: 4,
            tick_labels: Arc::from([]),
            label: None,
            style: Style::default(),
        }
    }
}

impl ChartAxis {
    /// Create default axis configuration.
    pub fn new() -> Self {
        Self::default()
    }

    /// Toggle axis visibility.
    pub fn show(mut self, show: bool) -> Self {
        self.show = show;
        self
    }

    /// Set explicit numeric range.
    pub fn range(mut self, min: f64, max: f64) -> Self {
        self.min = Some(min);
        self.max = Some(max);
        self
    }

    /// Set preferred tick count.
    pub fn ticks(mut self, ticks: u16) -> Self {
        self.ticks = ticks.max(2);
        self
    }

    /// Replace the numeric endpoint labels with explicit tick labels.
    ///
    /// Labels are spread evenly across the axis: the first sits at the low end,
    /// the last at the high end, the rest centred on their fractional position.
    /// A label that would collide with the previous one is skipped, so a dense
    /// set degrades gracefully in a narrow plot instead of overprinting.
    pub fn tick_labels<S: Into<Arc<str>>>(mut self, labels: impl IntoIterator<Item = S>) -> Self {
        self.tick_labels = labels.into_iter().map(Into::into).collect();
        self
    }

    /// Set optional axis label.
    pub fn label(mut self, label: impl Into<Arc<str>>) -> Self {
        self.label = Some(label.into());
        self
    }

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

/// Horizontal threshold reference line.
#[derive(Clone, Debug)]
pub struct ChartThreshold {
    pub(crate) value: f64,
    pub(crate) label: Option<Arc<str>>,
    pub(crate) style: Style,
    pub(crate) glyph: char,
}

impl ChartThreshold {
    /// Create a new threshold line at a numeric value.
    pub fn new(value: f64) -> Self {
        Self {
            value,
            label: None,
            style: Style::default(),
            glyph: '',
        }
    }

    /// Set threshold label.
    pub fn label(mut self, label: impl Into<Arc<str>>) -> Self {
        self.label = Some(label.into());
        self
    }

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

    /// Set glyph used for the threshold line.
    pub fn glyph(mut self, glyph: char) -> Self {
        self.glyph = glyph;
        self
    }
}

/// Multi-series chart with axes, grid, legend, and thresholds.
#[derive(Clone)]
pub struct Chart {
    pub(crate) series: Arc<[ChartSeries]>,
    pub(crate) thresholds: Arc<[ChartThreshold]>,
    pub(crate) x_axis: ChartAxis,
    pub(crate) y_axis: ChartAxis,
    pub(crate) style: Style,
    pub(crate) axis_style: Style,
    pub(crate) grid_style: Style,
    pub(crate) legend_style: Style,
    pub(crate) show_grid: bool,
    pub(crate) show_legend: bool,
    pub(crate) legend_separator: Arc<str>,
    pub(crate) viewport_start: usize,
    pub(crate) viewport_len: Option<usize>,
    /// Padding inside the chart frame.
    /// Default: `Padding::default()`.
    pub(crate) padding: Padding,
    pub(crate) border: bool,
    /// Border style.
    /// Default: `BorderStyle::Plain`.
    pub(crate) border_style: BorderStyle,
    /// Requested width.
    /// Default: `Length::Flex(1)`.
    pub(crate) width: Length,
    /// Requested height.
    /// Default: `Length::Px(10)`.
    pub(crate) height: Length,
}

impl Default for Chart {
    fn default() -> Self {
        Self {
            series: Arc::new([]),
            thresholds: Arc::new([]),
            x_axis: ChartAxis::default(),
            y_axis: ChartAxis::default(),
            style: Style::default(),
            axis_style: Style::default(),
            grid_style: Style::default(),
            legend_style: Style::default(),
            show_grid: true,
            show_legend: true,
            legend_separator: Arc::from("  "),
            viewport_start: 0,
            viewport_len: None,
            padding: Padding::default(),
            border: false,
            border_style: BorderStyle::Plain,
            width: Length::Flex(1),
            height: Length::Px(10),
        }
    }
}

impl Chart {
    /// Create an empty chart.
    pub fn new() -> Self {
        Self::default()
    }

    /// Replace all chart series.
    pub fn series(mut self, series: impl IntoIterator<Item = ChartSeries>) -> Self {
        self.series = series.into_iter().collect::<Vec<_>>().into();
        self
    }

    /// Set series from a shared slice.
    pub fn series_arc(mut self, series: Arc<[ChartSeries]>) -> Self {
        self.series = series;
        self
    }

    /// Add one chart series.
    pub fn add_series(mut self, series: ChartSeries) -> Self {
        let mut next = self.series.to_vec();
        next.push(series);
        self.series = next.into();
        self
    }

    /// Replace threshold definitions.
    pub fn thresholds(mut self, thresholds: impl IntoIterator<Item = ChartThreshold>) -> Self {
        self.thresholds = thresholds.into_iter().collect::<Vec<_>>().into();
        self
    }

    /// Set X axis config.
    pub fn x_axis(mut self, axis: ChartAxis) -> Self {
        self.x_axis = axis;
        self
    }

    /// Set Y axis config.
    pub fn y_axis(mut self, axis: ChartAxis) -> Self {
        self.y_axis = axis;
        self
    }

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

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

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

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

    /// Toggle plot grid rendering.
    pub fn show_grid(mut self, show_grid: bool) -> Self {
        self.show_grid = show_grid;
        self
    }

    /// Toggle legend rendering.
    pub fn show_legend(mut self, show_legend: bool) -> Self {
        self.show_legend = show_legend;
        self
    }

    /// Set separator between legend items.
    pub fn legend_separator(mut self, legend_separator: impl Into<Arc<str>>) -> Self {
        self.legend_separator = legend_separator.into();
        self
    }

    /// Set viewport start index.
    pub fn viewport_start(mut self, viewport_start: usize) -> Self {
        self.viewport_start = viewport_start;
        self
    }

    /// Set optional viewport sample length.
    pub fn viewport_len(mut self, viewport_len: Option<usize>) -> Self {
        self.viewport_len = viewport_len;
        self
    }

    /// Set chart padding.
    pub fn padding(mut self, padding: impl Into<Padding>) -> Self {
        self.padding = padding.into();
        self
    }

    /// Enable or disable chart border.
    pub fn border(mut self, border: bool) -> Self {
        self.border = border;
        self
    }

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

    /// Set requested chart width.
    pub fn width(mut self, width: Length) -> Self {
        self.width = width;
        self
    }

    /// Set requested chart height.
    pub fn height(mut self, height: Length) -> Self {
        self.height = height;
        self
    }
}

impl From<Chart> for Element {
    fn from(value: Chart) -> Self {
        Element::new(ElementKind::Chart(Box::new(value)))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Arc;

    #[test]
    fn series_arc_preserves_shared_slice() {
        let series: Arc<[ChartSeries]> = Arc::from([ChartSeries::new("cpu", [1.0, 2.0, 3.0])]);
        let chart = Chart::new().series_arc(Arc::clone(&series));
        assert!(Arc::ptr_eq(&chart.series, &series));
    }

    #[test]
    fn chart_series_data_arc_preserves_shared_slice() {
        let data: Arc<[f64]> = Arc::from([1.0, 2.0, 3.0]);
        let series = ChartSeries::new("cpu", []).data_arc(Arc::clone(&data));
        assert!(Arc::ptr_eq(&series.data, &data));
    }
}