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
use super::get_screen_width;
use term_grid::{Cell, Direction, Filling, Grid as LibGrid, GridOptions};

pub struct Grid {
    capacity: usize,
    grid: LibGrid,
    term_width: Option<usize>,
}

impl Grid {
    pub fn new(capacity: usize) -> Self {
        let mut grid = LibGrid::new(GridOptions {
            direction: Direction::TopToBottom,
            filling: Filling::Spaces(2),
        });
        grid.reserve(capacity);
        Self {
            grid,
            capacity,
            term_width: None,
        }
    }
    pub fn add(&mut self, contents: String, width: usize) {
        let cell = Cell { contents, width };
        self.grid.add(cell);
    }
    pub fn clear(&mut self) {
        *self = Grid::new(self.capacity);
    }
    pub fn fit_into_screen<'a>(&'a mut self) -> impl std::fmt::Display + 'a {
        if self.term_width.is_none() {
            let w = get_screen_width();
            self.term_width = Some(w as usize);
        }

        let width = self.term_width.unwrap();
        if width > 0 {
            if let Some(grid_display) = self.grid.fit_into_width(width) {
                return grid_display;
            }
        }
        self.grid.fit_into_columns(1)
    }
}