-
Notifications
You must be signed in to change notification settings - Fork 4
/
file_preview.rs
89 lines (75 loc) · 2.48 KB
/
file_preview.rs
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
use std::{
fs::read_to_string,
io::{self, stdout},
path::Path,
};
use crossterm::{
event::{read, Event, KeyCode},
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
ExecutableCommand,
};
use ratatui::{prelude::*, widgets::*};
use ratatui_explorer::{FileExplorer, Theme};
fn main() -> io::Result<()> {
enable_raw_mode()?;
stdout().execute(EnterAlternateScreen)?;
let mut terminal = Terminal::new(CrosstermBackend::new(stdout()))?;
let layout = Layout::horizontal([Constraint::Ratio(1, 3), Constraint::Ratio(2, 3)]);
// Create a new file explorer with the default theme and title.
let theme = get_theme();
let mut file_explorer = FileExplorer::with_theme(theme)?;
loop {
// Get the content of the current selected file (if it's indeed a file).
let file_content = get_file_content(file_explorer.current().path())?;
// Render the file explorer widget and the file content.
terminal.draw(|f| {
let chunks = layout.split(f.area());
f.render_widget(&file_explorer.widget(), chunks[0]);
f.render_widget(
Paragraph::new(file_content).block(
Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Double),
),
chunks[1],
);
})?;
// Read the next event from the terminal.
let event = read()?;
if let Event::Key(key) = event {
if key.code == KeyCode::Char('q') {
break;
}
}
// Handle the event in the file explorer.
file_explorer.handle(&event)?;
}
disable_raw_mode()?;
stdout().execute(LeaveAlternateScreen)?;
Ok(())
}
fn get_file_content(path: &Path) -> io::Result<String> {
let mut content = String::new();
// If the path is a file, read its content.
if path.is_file() {
content = read_to_string(path)?;
}
Ok(content)
}
fn get_theme() -> Theme {
Theme::default()
.with_block(
Block::default().borders(Borders::ALL),
)
.with_dir_style(
Style::default()
.fg(Color::White)
.add_modifier(Modifier::BOLD),
)
.with_highlight_dir_style(
Style::default()
.fg(Color::White)
.add_modifier(Modifier::BOLD)
.bg(Color::DarkGray),
)
}