ratatui_app/
ratatui_app.rs

1use std::io::{self, stdout};
2
3use ratatui::crossterm::event::{self, Event, KeyCode, KeyEventKind};
4use ratatui::style::{Color, Style};
5use ratatui::text::{Line, Text};
6use ratatui::{DefaultTerminal, Frame};
7use termprofile::{DetectorSettings, TermProfile};
8
9fn main() -> io::Result<()> {
10    // NOTE: it's important to detect the profile before initializing the terminal since the
11    // detection process may affect the terminal state.
12    let profile = TermProfile::detect(&stdout(), DetectorSettings::with_query()?);
13
14    let terminal = ratatui::init();
15    let result = run(terminal, profile);
16    ratatui::restore();
17    result
18}
19
20fn run(mut terminal: DefaultTerminal, profile: TermProfile) -> io::Result<()> {
21    loop {
22        terminal.draw(|f| draw(&profile, f))?;
23        if let Event::Key(key) = event::read()?
24            && key.kind == KeyEventKind::Press
25            && key.code == KeyCode::Char('q')
26        {
27            break Ok(());
28        }
29    }
30}
31
32fn draw(profile: &TermProfile, frame: &mut Frame) {
33    let color = Color::Rgb(rand_rgb(), rand_rgb(), rand_rgb());
34    let style = profile.adapt_style(Style::new().fg(color));
35
36    frame.render_widget(
37        Text::from_iter([
38            Line::raw("try using NO_COLOR and FORCE_COLOR to change the output"),
39            Line::raw(""),
40            Line::styled(
41                format!(
42                    "random color: {}",
43                    style.fg.map(|f| f.to_string()).unwrap_or("N/A".to_string())
44                ),
45                style,
46            ),
47        ]),
48        frame.area(),
49    );
50}
51
52fn rand_rgb() -> u8 {
53    rand::random_range(0..256) as u8
54}