| 1 |
use std::{ |
| 2 |
borrow::Cow, |
| 3 |
fs::read_to_string, |
| 4 |
io::{self, stdout}, |
| 5 |
}; |
| 6 |
|
| 7 |
use crossterm::{ |
| 8 |
ExecutableCommand, |
| 9 |
event::{Event, KeyCode, read}, |
| 10 |
terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode}, |
| 11 |
}; |
| 12 |
use ratatui::crossterm; |
| 13 |
use ratatui::{ |
| 14 |
prelude::*, |
| 15 |
widgets::{Block, BorderType, Borders, Clear, FrameExt, Paragraph}, |
| 16 |
}; |
| 17 |
|
| 18 |
use ratatui_explorer::{File, FileExplorerBuilder, Theme}; |
| 19 |
|
| 20 |
fn main() -> io::Result<()> { |
| 21 |
enable_raw_mode()?; |
| 22 |
stdout().execute(EnterAlternateScreen)?; |
| 23 |
|
| 24 |
let mut terminal = Terminal::new(CrosstermBackend::new(stdout()))?; |
| 25 |
let layout = Layout::horizontal([Constraint::Ratio(1, 3), Constraint::Ratio(2, 3)]); |
| 26 |
|
| 27 |
|
| 28 |
let mut file_explorer = FileExplorerBuilder::default() |
| 29 |
.theme(get_theme()) |
| 30 |
.show_hidden(true) |
| 31 |
.build()?; |
| 32 |
|
| 33 |
loop { |
| 34 |
|
| 35 |
let file_content = get_file_content(file_explorer.current()); |
| 36 |
|
| 37 |
let file_content = match file_content { |
| 38 |
Ok(file_content) => file_content, |
| 39 |
_ => "Couldn't load file.".into(), |
| 40 |
}; |
| 41 |
|
| 42 |
|
| 43 |
terminal.draw(|f| { |
| 44 |
let chunks = layout.split(f.area()); |
| 45 |
|
| 46 |
f.render_widget_ref(file_explorer.widget(), chunks[0]); |
| 47 |
f.render_widget(Clear, chunks[1]); |
| 48 |
f.render_widget( |
| 49 |
Paragraph::new(file_content).block( |
| 50 |
Block::default() |
| 51 |
.borders(Borders::ALL) |
| 52 |
.border_type(BorderType::Double), |
| 53 |
), |
| 54 |
chunks[1], |
| 55 |
); |
| 56 |
})?; |
| 57 |
|
| 58 |
|
| 59 |
let event = read()?; |
| 60 |
if let Event::Key(key) = event |
| 61 |
&& key.code == KeyCode::Char('q') |
| 62 |
{ |
| 63 |
break; |
| 64 |
} |
| 65 |
|
| 66 |
file_explorer.handle(&event)?; |
| 67 |
} |
| 68 |
|
| 69 |
disable_raw_mode()?; |
| 70 |
stdout().execute(LeaveAlternateScreen)?; |
| 71 |
Ok(()) |
| 72 |
} |
| 73 |
|
| 74 |
fn get_file_content(file: &File) -> io::Result<Cow<'_, str>> { |
| 75 |
|
| 76 |
if file.is_file() { |
| 77 |
read_to_string(&file.path).map(Into::into) |
| 78 |
} else if file.is_dir { |
| 79 |
Ok("".into()) |
| 80 |
} else { |
| 81 |
Ok("<not a regular file>".into()) |
| 82 |
} |
| 83 |
} |
| 84 |
|
| 85 |
fn get_theme() -> Theme { |
| 86 |
Theme::default() |
| 87 |
.with_dir_style( |
| 88 |
Style::default() |
| 89 |
.fg(Color::White) |
| 90 |
.add_modifier(Modifier::BOLD), |
| 91 |
) |
| 92 |
.with_highlight_dir_style( |
| 93 |
Style::default() |
| 94 |
.fg(Color::White) |
| 95 |
.add_modifier(Modifier::BOLD) |
| 96 |
.bg(Color::DarkGray), |
| 97 |
) |
| 98 |
.with_scroll_padding(1) |
| 99 |
} |