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
use crossterm::{
    event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind},
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{
    backend::{Backend, CrosstermBackend},
    prelude::*,
    widgets::{Block, Borders, Paragraph, Tabs, Widget},
};
use std::{error::Error, io};
use tui_widget_list::{List, ListState, Listable};

#[derive(Debug, Clone)]
pub struct ParagraphItem<'a> {
    paragraph: Paragraph<'a>,
    height: u16,
}

impl ParagraphItem<'_> {
    pub fn new(text: &str, height: u16) -> Self {
        let paragraph = Paragraph::new(vec![Line::from(Span::styled(
            text.to_string(),
            Style::default().fg(Color::Cyan),
        ))])
        .style(Style::default().bg(Color::Black))
        .block(Block::default().borders(Borders::ALL).title("Inner block"));
        Self { paragraph, height }
    }

    pub fn style(mut self, style: Style) -> Self {
        self.paragraph = self.paragraph.set_style(style);
        self
    }
}

impl Listable for ParagraphItem<'_> {
    fn height(&self) -> usize {
        self.height as usize
    }

    fn highlight(self) -> Self {
        let style = Style::default().bg(Color::White);
        self.style(style)
    }
}

impl Widget for ParagraphItem<'_> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        self.paragraph.render(area, buf);
    }
}

#[derive(Debug, Clone)]
pub struct TabItem {
    titles: Vec<String>,
    selected: bool,
}

impl TabItem {
    pub fn new(titles: Vec<String>) -> Self {
        Self {
            titles,
            selected: false,
        }
    }
}

impl Listable for TabItem {
    fn height(&self) -> usize {
        3
    }

    fn highlight(self) -> Self {
        Self {
            titles: self.titles,
            selected: true,
        }
    }
}

impl Widget for TabItem {
    fn render(self, area: Rect, buf: &mut Buffer) {
        let mut tabs =
            Tabs::new(self.titles).block(Block::default().borders(Borders::ALL).title("Tabs"));
        if self.selected {
            tabs = tabs
                .highlight_style(Style::default().bold().on_black())
                .style(Style::default().on_dark_gray());
        }
        tabs.render(area, buf);
    }
}

#[derive(Clone)]
enum ListElements<'a> {
    TabItem(TabItem),
    ParagraphItem(ParagraphItem<'a>),
}

impl Listable for ListElements<'_> {
    fn height(&self) -> usize {
        match &self {
            Self::TabItem(inner) => inner.height(),
            Self::ParagraphItem(inner) => inner.height(),
        }
    }

    fn highlight(self) -> Self {
        match self {
            Self::TabItem(inner) => Self::TabItem(inner.highlight()),
            Self::ParagraphItem(inner) => Self::ParagraphItem(inner.highlight()),
        }
    }
}

impl Widget for ListElements<'_> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        match self {
            Self::TabItem(inner) => inner.render(area, buf),
            Self::ParagraphItem(inner) => inner.render(area, buf),
        };
    }
}

type Result<T> = std::result::Result<T, Box<dyn Error>>;

fn main() -> Result<()> {
    let mut terminal = init_terminal()?;

    let app = App::new();
    run_app(&mut terminal, app).unwrap();

    reset_terminal()?;
    terminal.show_cursor()?;

    Ok(())
}

/// Initializes the terminal.
fn init_terminal() -> Result<Terminal<CrosstermBackend<io::Stdout>>> {
    crossterm::execute!(io::stdout(), EnterAlternateScreen, EnableMouseCapture)?;
    enable_raw_mode()?;

    let backend = CrosstermBackend::new(io::stdout());

    let mut terminal = Terminal::new(backend)?;
    terminal.hide_cursor()?;

    panic_hook();

    Ok(terminal)
}

/// Resets the terminal.
fn reset_terminal() -> Result<()> {
    disable_raw_mode()?;
    crossterm::execute!(io::stdout(), LeaveAlternateScreen, DisableMouseCapture)?;

    Ok(())
}

/// Shutdown gracefully
fn panic_hook() {
    let original_hook = std::panic::take_hook();

    std::panic::set_hook(Box::new(move |panic| {
        reset_terminal().unwrap();
        original_hook(panic);
    }));
}

pub struct App<'a> {
    list: List<'a, ListElements<'a>>,
    state: ListState,
}

impl<'a> App<'a> {
    pub fn new() -> App<'a> {
        let items = vec![
            ListElements::ParagraphItem(ParagraphItem::new("Height: 4", 4)),
            ListElements::TabItem(TabItem::new(vec![
                "Item A".to_string(),
                "Item B".to_string(),
            ])),
            ListElements::ParagraphItem(ParagraphItem::new("Height: 6", 6)),
        ];
        let list = List::new(items)
            .style(Style::default().bg(Color::Black))
            .block(Block::default().borders(Borders::ALL).title("Outer block"))
            .truncate(true);
        let state = ListState::default();
        App { list, state }
    }
}

pub fn run_app<B: Backend>(terminal: &mut Terminal<B>, mut app: App) -> io::Result<()> {
    loop {
        terminal.draw(|f| ui(f, &mut app))?;

        if let Event::Key(key) = event::read()? {
            if key.kind == KeyEventKind::Press {
                match key.code {
                    KeyCode::Char('q') => return Ok(()),
                    KeyCode::Up => app.state.previous(),
                    KeyCode::Down => app.state.next(),
                    _ => {}
                }
            }
        }
    }
}

pub fn ui(f: &mut Frame, app: &mut App) {
    let list = app.list.clone();
    f.render_stateful_widget(list, f.size(), &mut app.state);
}