ttygrid 0.3.0

Grid layout engine for tabular data displayed in a TTY
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
//! ttygrid provides functionality for displaying table-ized text to users with
//! appropriate padding and width management. With ttygrid, you merely need to feed it your data,
//! some information about the precedence (called a "priority") of each column, and it will
//! automatically determine what to show to the user based on the available display width. See
//! [crate::grid!] for more information.
//!
//! [Here](https://asciinema.org/a/609115) is a demo to see the results in action.
//!
//! It is not intended for streaming (aka, not tty) situations. It probably only works on unix
//! right now too.
//!
//! The [`demo example`]
//! some basic capabilities and should be reviewed for understanding this library; as well as
//! learning the macros.
//!
//! [`demo example`]: https://github.com/erikh/ttygrid/blob/main/examples/demo.rs
//!
//! Much of this library relies on the macros, not the types directly. Please review those for the
//! most comprehensive documentation.
use anyhow::{anyhow, Result};
use crossterm::{
    execute,
    style::{Color, Colors, Print, SetColors},
};
use std::{cell::RefCell, fmt, rc::Rc, usize::MAX};

mod macros;
pub use macros::*;

pub type SafeGridHeader = Rc<RefCell<GridHeader>>;

/// HeaderList defines a list of headers. This is typically composed as a part of the process from
/// [crate::header!] and [crate::grid!] and is not constructed directly.
#[derive(Default, Clone, Eq, PartialEq, PartialOrd, Ord)]
pub struct HeaderList(Vec<SafeGridHeader>);

impl HeaderList {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn is_empty(&self) -> bool {
        self.0.len() == 0
    }

    pub fn len(&self) -> usize {
        self.0.len()
    }

    pub fn get(&self, idx: usize) -> Option<&SafeGridHeader> {
        self.0.get(idx)
    }
}

impl fmt::Display for HeaderList {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        for header in self.0.clone() {
            write!(
                formatter,
                "{:<width$}",
                header.borrow().text,
                width = header
                    .borrow()
                    .max_len
                    .unwrap_or(header.borrow().text.len() + 2)
            )?
        }
        Ok(())
    }
}

/// GridHeader encapsulates the properties of a header, such as priority and padding information.
/// This is typically constructed by [crate::header!] and is not constructed directly.
///
/// Several methods can adjust the content of the header after the fact, and should be reviewed.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct GridHeader {
    index: Option<usize>,
    text: &'static str,
    min_size: Option<usize>,
    max_pad: Option<usize>,
    priority: usize,
    max_len: Option<usize>,
}

impl Default for GridHeader {
    fn default() -> Self {
        Self {
            index: None,
            text: "",
            min_size: None,
            max_pad: Some(4),
            priority: 0,
            max_len: None,
        }
    }
}

impl PartialOrd for GridHeader {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        if self.index.is_some() {
            Some(
                self.priority
                    .cmp(&other.priority)
                    .then(self.index.cmp(&other.index)),
            )
        } else {
            Some(self.priority.cmp(&other.priority))
        }
    }
}

impl Ord for GridHeader {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        if self.index.is_some() {
            self.priority
                .cmp(&other.priority)
                .then(self.index.cmp(&other.index))
        } else {
            self.priority.cmp(&other.priority)
        }
    }
}

impl GridHeader {
    /// Set the maximum length of items belonging to this header.
    pub fn set_max_len(&mut self, len: usize) {
        self.max_len = Some(len)
    }

    /// Set the text of this header.
    pub fn set_text(mut self, text: &'static str) -> Self {
        self.text = text;
        self
    }

    /// Set the priority of this header. Higher priority items will be more likely to be shown on
    /// smaller terminal sizes.
    pub fn set_priority(mut self, priority: usize) -> Self {
        self.priority = priority;
        self
    }

    /// Set the position this header lives within the column list. 0 is the first position.
    pub fn set_index(&mut self, idx: usize) {
        self.index = Some(idx);
    }

    pub fn text(&self) -> &str {
        self.text.clone()
    }

    pub fn priority(&self) -> usize {
        self.priority
    }
}

/// GridItem is the encapsulation of a piece of content. It is usually created by invoking
/// [crate::add_line!] and is not instantiated directly.
#[derive(Clone, Debug, Default)]
pub struct GridItem {
    header: SafeGridHeader,
    contents: String,
    max_len: Option<usize>,
}

impl GridItem {
    pub fn new(header: SafeGridHeader, contents: String) -> Self {
        Self {
            header,
            contents,
            max_len: None,
        }
    }

    fn len(&self) -> usize {
        self.contents.len() + 1 // right padding
    }

    fn set_max_len(&mut self, max_len: usize) {
        self.max_len = Some(max_len)
    }
}

impl fmt::Display for GridItem {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(
            formatter,
            "{:<max_len$}",
            self.contents,
            max_len = self.max_len.unwrap_or(self.len())
        )
    }
}

/// Usually constructed by [crate::grid!], this is the outer object of the whole library, all
/// things are held by it in some form. Please review the impl for methods which can be used to
/// adjust the properties of the grid once created.
#[derive(Clone)]
pub struct TTYGrid {
    headers: HeaderList,
    selected: HeaderList,
    lines: Vec<GridLine>,
    width: usize,
    header_color: Colors,
    delimiter_color: Colors,
    primary_color: Colors,
    secondary_color: Colors,
}

impl TTYGrid {
    pub fn new(headers: Vec<SafeGridHeader>) -> Result<Self> {
        let (w, _) = crossterm::terminal::size()?;
        let width = w as usize;

        Ok(Self {
            selected: HeaderList::new(),
            headers: HeaderList(headers),
            lines: Vec::new(),
            width,
            header_color: Colors::new(Color::Reset, Color::Reset),
            delimiter_color: Colors::new(Color::Reset, Color::Reset),
            primary_color: Colors::new(Color::Reset, Color::Reset),
            secondary_color: Colors::new(Color::Reset, Color::Reset),
        })
    }

    /// Sets the delimiter color; the dashes between the header and the content.
    pub fn set_delimiter_color(&mut self, colors: Colors) {
        self.delimiter_color = colors
    }

    /// Sets the header color.
    pub fn set_header_color(&mut self, colors: Colors) {
        self.header_color = colors
    }

    /// Sets the primary color; colors will alternate between primary and secondary per row as the
    /// table is built.
    pub fn set_primary_color(&mut self, colors: Colors) {
        self.primary_color = colors
    }

    /// Sets the secondary color; colors will alternate between primary and secondary per row as
    /// the table is built.
    pub fn set_secondary_color(&mut self, colors: Colors) {
        self.secondary_color = colors
    }

    pub fn add_line(&mut self, item: GridLine) {
        self.lines.push(item)
    }

    pub fn clear_lines(&mut self) {
        self.lines.clear()
    }

    pub fn headers(&self) -> HeaderList {
        self.headers.clone()
    }

    pub fn select(&mut self, header: SafeGridHeader, idx: usize) {
        // update index (still an issue)
        header.borrow_mut().set_index(idx);
        self.selected.0.push(header)
    }

    pub fn is_selected(&self, header: SafeGridHeader) -> bool {
        self.selected.0.contains(&header)
    }

    pub fn select_all_headers(&mut self) {
        self.selected = self.headers.clone()
    }

    pub fn deselect_all_headers(&mut self) {
        self.selected.0.clear()
    }

    fn set_grid_max_len(&mut self, len_map: &LengthMapper) -> Result<()> {
        let mut cached_columns = Vec::new();

        for (idx, header) in self.headers.0.iter_mut().enumerate() {
            let max_len = len_map.max_len_for_column(&header.borrow())?;
            header.borrow_mut().set_max_len(max_len);
            cached_columns.insert(idx, header.borrow().max_len);
        }

        for line in self.lines.iter_mut() {
            for (idx, item) in line.0.iter_mut().enumerate() {
                if let Some(column) = cached_columns.get(idx) {
                    item.set_max_len(column.unwrap());
                }
            }
        }

        Ok(())
    }

    fn determine_headers(&mut self) -> Result<()> {
        let mut len_map = LengthMapper::default();
        len_map.map_lines(self.lines.clone());

        self.set_grid_max_len(&len_map)?; // this has to happen before any return occurs
        let last = len_map.max_len_for_headers(self.headers.clone())?;

        if last <= self.width {
            self.select_all_headers();
            return Ok(());
        }

        let mut prio_map: Vec<(usize, (HeaderList, usize))> = Vec::new();
        self.deselect_all_headers();

        let mut len = self.headers.0.len();

        while len > 0 {
            let mut headers = HeaderList::new();
            for header in self.headers.0.iter().take(len) {
                headers.0.push(header.clone())
            }

            let mut max_len = len_map.max_len_for_headers(headers.clone())?;

            while max_len > self.width {
                let mut new_headers = headers.clone();
                let mut lowest_prio_index = MAX;
                let mut to_remove = None;

                for (idx, header) in new_headers.0.iter().enumerate() {
                    let priority = header.borrow().priority;
                    if priority < lowest_prio_index {
                        to_remove = Some(idx);
                        lowest_prio_index = priority;
                    }
                }

                if let Some(to_remove) = to_remove {
                    new_headers.0.remove(to_remove);
                    max_len = len_map.max_len_for_headers(new_headers.clone())?;
                    headers = new_headers;
                } else {
                    max_len = 0 // bury it
                }
            }

            let index = headers.0.iter().fold(0, |acc, x| acc + x.borrow().priority);
            prio_map.push((index, (headers, max_len)));
            len -= 1;
        }

        if prio_map.is_empty() {
            return Err(anyhow!("your terminal is too small"));
        }

        prio_map.sort();

        let (_, (max_headers, _)) = prio_map.iter().last().unwrap();

        for (idx, header) in max_headers.0.iter().enumerate() {
            self.select(header.clone(), idx);
        }

        Ok(())
    }

    /// Yield a string which is suitable for passing to [println!], but does not make any attempt
    /// to add terminal styling, which may be better for situations where data is piped. Unlike
    /// [std::fmt::Display], this display method returns `Result<String, anyhow::Error>`.
    pub fn display(&mut self) -> Result<String> {
        self.determine_headers()?;
        Ok(format!("{}", self))
    }

    /// Write to the writer, typically [std::io::stdout]. Terminal colors will be set.
    pub fn write(&mut self, mut writer: impl std::io::Write) -> Result<()> {
        self.determine_headers()?;
        execute!(
            writer,
            SetColors(self.header_color),
            Print(&format!("{}\n", self.selected))
        )?;
        execute!(
            writer,
            SetColors(self.delimiter_color),
            Print(&format!("{:-<width$}\n", "-", width = self.width))
        )?;

        for (idx, line) in self.lines.iter().enumerate() {
            if idx % 2 == 0 {
                execute!(writer, SetColors(self.primary_color))?;
            } else {
                execute!(writer, SetColors(self.secondary_color))?;
            }
            execute!(writer, Print(&format!("{}\n", line.selected(self))))?;
        }

        Ok(())
    }
}

impl fmt::Display for TTYGrid {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        writeln!(formatter, "{}", self.selected)?;
        writeln!(formatter, "{:-<width$}", "-", width = self.width)?;

        for line in self.lines.clone() {
            writeln!(formatter, "{}", line.selected(self))?
        }

        Ok(())
    }
}

/// A collection of grid items. Usually instantiated by [crate::add_line!].
#[derive(Clone, Default, Debug)]
pub struct GridLine(pub Vec<GridItem>);

impl GridLine {
    fn selected(&self, grid: &TTYGrid) -> Self {
        let mut ret = Vec::new();
        for item in self.0.iter() {
            if grid.is_selected(item.header.clone()) {
                ret.push(item.clone())
            }
        }

        GridLine(ret)
    }
}

impl fmt::Display for GridLine {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        for contents in self.0.clone() {
            write!(formatter, "{}", contents)?
        }

        Ok(())
    }
}

#[derive(Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
struct LengthMapper(Vec<Vec<(SafeGridHeader, usize)>>);

impl LengthMapper {
    fn map_lines(&mut self, lines: Vec<GridLine>) {
        for line in lines.clone() {
            let len = self.0.len();
            self.0.push(Vec::new()); // now len is equal to index
            for item in line.0 {
                self.0
                    .get_mut(len)
                    .unwrap()
                    .push((item.header.clone(), item.len()));
            }
        }
    }

    fn max_len_for_column(&self, header: &GridHeader) -> Result<usize> {
        let mut max_len = 0;
        for line in self.0.clone() {
            let found = line.iter().find(|i| i.0.borrow().eq(header));

            if found.is_none() {
                return Err(anyhow!(
                    "panic: cannot find pre-existing column in line, report this bug"
                ));
            }

            if max_len < found.unwrap().1 {
                max_len = found.unwrap().1
            }
        }

        Ok(max_len + header.max_pad.unwrap_or(0) + 2)
    }

    fn max_len_for_headers(&mut self, headers: HeaderList) -> Result<usize> {
        Ok(headers.0.iter().fold(0, |x, h| {
            x + self
                .max_len_for_column(&h.clone().borrow())
                .unwrap_or_default()
        }))
    }
}