-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathdemo.rs
419 lines (394 loc) Β· 13.6 KB
/
demo.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
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
use std::path::{Path, PathBuf};
use std::time::Duration;
use tui_realm_stdlib::{Input, Phantom};
use tuirealm::terminal::CrosstermTerminalAdapter;
use tuirealm::{
application::PollStrategy,
command::{Cmd, CmdResult, Direction, Position},
event::{Event, Key, KeyEvent, KeyModifiers},
props::{Alignment, AttrValue, Attribute, BorderType, Borders, Color, InputType, Style},
terminal::TerminalBridge,
Application, Component, EventListenerCfg, MockComponent, NoUserEvent, State, StateValue, Sub,
SubClause, SubEventClause, Update,
};
// tui
use tuirealm::ratatui::layout::{Constraint, Direction as LayoutDirection, Layout};
// treeview
use tui_realm_treeview::{Node, Tree, TreeView, TREE_CMD_CLOSE, TREE_CMD_OPEN};
const MAX_DEPTH: usize = 3;
// -- message
#[derive(Debug, PartialEq)]
pub enum Msg {
AppClose,
ExtendDir(String),
FsTreeBlur,
GoToBlur,
GoTo(PathBuf),
GoToUpperDir,
None,
}
// Let's define the component ids for our application
#[derive(Debug, Eq, PartialEq, Clone, Hash)]
pub enum Id {
FsTree,
GlobalListener,
GoTo,
}
struct Model {
app: Application<Id, Msg, NoUserEvent>,
path: PathBuf,
tree: Tree<String>, // You can choose a Tree<Vec<TextSpan>> for more flexible rendering
quit: bool, // Becomes true when the user presses <ESC>
redraw: bool, // Tells whether to refresh the UI; performance optimization
terminal: TerminalBridge<CrosstermTerminalAdapter>,
}
impl Model {
fn new(p: &Path) -> Self {
// Setup app
let mut app: Application<Id, Msg, NoUserEvent> = Application::init(
EventListenerCfg::default().crossterm_input_listener(Duration::from_millis(10), 10),
);
assert!(app
.mount(
Id::FsTree,
Box::new(FsTree::new(Tree::new(Self::dir_tree(p, MAX_DEPTH)), None)),
vec![]
)
.is_ok());
assert!(app
.mount(Id::GoTo, Box::new(GoTo::default()), vec![])
.is_ok());
// Mount global listener which will listen for <ESC>
assert!(app
.mount(
Id::GlobalListener,
Box::new(GlobalListener::default()),
vec![Sub::new(
SubEventClause::Keyboard(KeyEvent {
code: Key::Esc,
modifiers: KeyModifiers::NONE,
}),
SubClause::Always
)]
)
.is_ok());
// We need to give focus to input then
assert!(app.active(&Id::FsTree).is_ok());
Model {
app,
quit: false,
redraw: true,
tree: Tree::new(Self::dir_tree(p, MAX_DEPTH)),
path: p.to_path_buf(),
terminal: TerminalBridge::init_crossterm().expect("Could not initialize terminal"),
}
}
pub fn scan_dir(&mut self, p: &Path) {
self.path = p.to_path_buf();
self.tree = Tree::new(Self::dir_tree(p, MAX_DEPTH));
}
pub fn upper_dir(&self) -> Option<PathBuf> {
self.path.parent().map(|x| x.to_path_buf())
}
pub fn extend_dir(&mut self, id: &String, p: &Path, depth: usize) {
if let Some(node) = self.tree.root_mut().query_mut(id) {
if depth > 0 && p.is_dir() {
// Clear node
node.clear();
// Scan dir
if let Ok(e) = std::fs::read_dir(p) {
e.flatten().for_each(|x| {
node.add_child(Self::dir_tree(x.path().as_path(), depth - 1))
});
}
}
}
}
fn dir_tree(p: &Path, depth: usize) -> Node<String> {
let name: String = match p.file_name() {
None => "/".to_string(),
Some(n) => n.to_string_lossy().into_owned().to_string(),
};
let mut node: Node<String> = Node::new(p.to_string_lossy().into_owned(), name);
if depth > 0 && p.is_dir() {
if let Ok(e) = std::fs::read_dir(p) {
e.flatten()
.for_each(|x| node.add_child(Self::dir_tree(x.path().as_path(), depth - 1)));
}
}
node
}
fn view(&mut self) {
let _ = self.terminal.raw_mut().draw(|f| {
// Prepare chunks
let chunks = Layout::default()
.direction(LayoutDirection::Vertical)
.margin(1)
.constraints([Constraint::Min(5), Constraint::Length(3)].as_ref())
.split(f.area());
self.app.view(&Id::FsTree, f, chunks[0]);
self.app.view(&Id::GoTo, f, chunks[1]);
});
}
fn reload_tree(&mut self) {
let current_node = match self.app.state(&Id::FsTree).ok().unwrap() {
State::One(StateValue::String(id)) => Some(id),
_ => None,
};
// Remount tree
assert!(self.app.umount(&Id::FsTree).is_ok());
assert!(self
.app
.mount(
Id::FsTree,
Box::new(FsTree::new(self.tree.clone(), current_node)),
vec![]
)
.is_ok());
assert!(self.app.active(&Id::FsTree).is_ok());
}
}
fn main() {
// Make model
let mut model: Model = Model::new(std::env::current_dir().ok().unwrap().as_path());
let _ = model.terminal.enable_raw_mode();
let _ = model.terminal.enter_alternate_screen();
// let's loop until quit is true
while !model.quit {
// Tick
if let Ok(messages) = model.app.tick(PollStrategy::Once) {
for msg in messages.into_iter() {
let mut msg = Some(msg);
while msg.is_some() {
msg = model.update(msg);
}
}
}
// Redraw
if model.redraw {
model.view();
model.redraw = false;
}
}
// Terminate terminal
let _ = model.terminal.restore();
}
// -- update
impl Update<Msg> for Model {
fn update(&mut self, msg: Option<Msg>) -> Option<Msg> {
self.redraw = true;
match msg.unwrap_or(Msg::None) {
Msg::AppClose => {
self.quit = true;
None
}
Msg::ExtendDir(path) => {
self.extend_dir(&path, PathBuf::from(path.as_str()).as_path(), MAX_DEPTH);
self.reload_tree();
None
}
Msg::GoTo(path) => {
// Go to and reload tree
self.scan_dir(path.as_path());
self.reload_tree();
None
}
Msg::GoToUpperDir => {
if let Some(parent) = self.upper_dir() {
self.scan_dir(parent.as_path());
self.reload_tree();
}
None
}
Msg::FsTreeBlur => {
assert!(self.app.active(&Id::GoTo).is_ok());
None
}
Msg::GoToBlur => {
assert!(self.app.active(&Id::FsTree).is_ok());
None
}
Msg::None => None,
}
}
}
// -- components
#[derive(MockComponent)]
pub struct FsTree {
component: TreeView<String>,
}
impl FsTree {
pub fn new(tree: Tree<String>, initial_node: Option<String>) -> Self {
// Preserve initial node if exists
let initial_node = match initial_node {
Some(id) if tree.root().query(&id).is_some() => id,
_ => tree.root().id().to_string(),
};
FsTree {
component: TreeView::default()
.foreground(Color::Reset)
.borders(
Borders::default()
.color(Color::LightYellow)
.modifiers(BorderType::Rounded),
)
.inactive(Style::default().fg(Color::Gray))
.indent_size(3)
.scroll_step(6)
.title(tree.root().id(), Alignment::Left)
.highlighted_color(Color::LightYellow)
.highlight_symbol("π¦")
.with_tree(tree)
.initial_node(initial_node),
}
}
}
impl Component<Msg, NoUserEvent> for FsTree {
fn on(&mut self, ev: Event<NoUserEvent>) -> Option<Msg> {
let result = match ev {
Event::Keyboard(KeyEvent {
code: Key::Left,
modifiers: KeyModifiers::NONE,
}) => self.perform(Cmd::Custom(TREE_CMD_CLOSE)),
Event::Keyboard(KeyEvent {
code: Key::Right,
modifiers: KeyModifiers::NONE,
}) => self.perform(Cmd::Custom(TREE_CMD_OPEN)),
Event::Keyboard(KeyEvent {
code: Key::PageDown,
modifiers: KeyModifiers::NONE,
}) => self.perform(Cmd::Scroll(Direction::Down)),
Event::Keyboard(KeyEvent {
code: Key::PageUp,
modifiers: KeyModifiers::NONE,
}) => self.perform(Cmd::Scroll(Direction::Up)),
Event::Keyboard(KeyEvent {
code: Key::Down,
modifiers: KeyModifiers::NONE,
}) => self.perform(Cmd::Move(Direction::Down)),
Event::Keyboard(KeyEvent {
code: Key::Up,
modifiers: KeyModifiers::NONE,
}) => self.perform(Cmd::Move(Direction::Up)),
Event::Keyboard(KeyEvent {
code: Key::Home,
modifiers: KeyModifiers::NONE,
}) => self.perform(Cmd::GoTo(Position::Begin)),
Event::Keyboard(KeyEvent {
code: Key::End,
modifiers: KeyModifiers::NONE,
}) => self.perform(Cmd::GoTo(Position::End)),
Event::Keyboard(KeyEvent {
code: Key::Enter,
modifiers: KeyModifiers::NONE,
}) => self.perform(Cmd::Submit),
Event::Keyboard(KeyEvent {
code: Key::Backspace,
modifiers: KeyModifiers::NONE,
}) => return Some(Msg::GoToUpperDir),
Event::Keyboard(KeyEvent {
code: Key::Tab,
modifiers: KeyModifiers::NONE,
}) => return Some(Msg::FsTreeBlur),
_ => return None,
};
match result {
CmdResult::Submit(State::One(StateValue::String(node))) => Some(Msg::ExtendDir(node)),
_ => Some(Msg::None),
}
}
}
// -- global listener
#[derive(Default, MockComponent)]
pub struct GlobalListener {
component: Phantom,
}
impl Component<Msg, NoUserEvent> for GlobalListener {
fn on(&mut self, ev: Event<NoUserEvent>) -> Option<Msg> {
match ev {
Event::Keyboard(KeyEvent {
code: Key::Esc,
modifiers: KeyModifiers::NONE,
}) => Some(Msg::AppClose),
_ => None,
}
}
}
// -- goto input
#[derive(MockComponent)]
pub struct GoTo {
component: Input,
}
impl Default for GoTo {
fn default() -> Self {
Self {
component: Input::default()
.foreground(Color::LightBlue)
.borders(
Borders::default()
.color(Color::LightBlue)
.modifiers(BorderType::Rounded),
)
.input_type(InputType::Text)
.placeholder(
"/foo/bar/buzz",
Style::default().fg(Color::Rgb(120, 120, 120)),
)
.title("Go to...", Alignment::Left),
}
}
}
impl Component<Msg, NoUserEvent> for GoTo {
fn on(&mut self, ev: Event<NoUserEvent>) -> Option<Msg> {
let result = match ev {
Event::Keyboard(KeyEvent {
code: Key::Enter,
modifiers: KeyModifiers::NONE,
}) => {
let res = self.perform(Cmd::Submit);
// Clear value
self.attr(Attribute::Value, AttrValue::String(String::new()));
res
}
Event::Keyboard(KeyEvent {
code: Key::Char(ch),
modifiers: KeyModifiers::NONE,
}) => self.perform(Cmd::Type(ch)),
Event::Keyboard(KeyEvent {
code: Key::Left,
modifiers: KeyModifiers::NONE,
}) => self.perform(Cmd::Move(Direction::Left)),
Event::Keyboard(KeyEvent {
code: Key::Right,
modifiers: KeyModifiers::NONE,
}) => self.perform(Cmd::Move(Direction::Right)),
Event::Keyboard(KeyEvent {
code: Key::Home,
modifiers: KeyModifiers::NONE,
}) => self.perform(Cmd::GoTo(Position::Begin)),
Event::Keyboard(KeyEvent {
code: Key::End,
modifiers: KeyModifiers::NONE,
}) => self.perform(Cmd::GoTo(Position::End)),
Event::Keyboard(KeyEvent {
code: Key::Delete,
modifiers: KeyModifiers::NONE,
}) => self.perform(Cmd::Cancel),
Event::Keyboard(KeyEvent {
code: Key::Backspace,
modifiers: KeyModifiers::NONE,
}) => self.perform(Cmd::Delete),
Event::Keyboard(KeyEvent {
code: Key::Tab,
modifiers: KeyModifiers::NONE,
}) => return Some(Msg::GoToBlur),
_ => return None,
};
match result {
CmdResult::Submit(State::One(StateValue::String(path))) => {
Some(Msg::GoTo(PathBuf::from(path.as_str())))
}
_ => Some(Msg::None),
}
}
}