forked from rhysd/tui-textarea
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsingle_line.rs
83 lines (75 loc) · 2.47 KB
/
single_line.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
use crossterm::event::{DisableMouseCapture, EnableMouseCapture};
use crossterm::terminal::{
disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
};
use std::io;
use tui::backend::CrosstermBackend;
use tui::layout::{Constraint, Layout};
use tui::style::{Color, Style};
use tui::widgets::{Block, Borders};
use tui::Terminal;
use tui_textarea::{Input, Key, TextArea};
fn validate(textarea: &mut TextArea) -> bool {
if let Err(err) = textarea.lines()[0].parse::<f64>() {
textarea.set_style(Style::default().fg(Color::LightRed));
textarea.set_block(
Block::default()
.borders(Borders::ALL)
.title(format!("ERROR: {}", err)),
);
false
} else {
textarea.set_style(Style::default().fg(Color::LightGreen));
textarea.set_block(Block::default().borders(Borders::ALL).title("OK"));
true
}
}
fn main() -> io::Result<()> {
let stdout = io::stdout();
let mut stdout = stdout.lock();
enable_raw_mode()?;
crossterm::execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
let backend = CrosstermBackend::new(stdout);
let mut term = Terminal::new(backend)?;
let mut textarea = TextArea::default();
textarea.set_cursor_line_style(Style::default());
let layout =
Layout::default().constraints([Constraint::Length(3), Constraint::Min(1)].as_slice());
let mut is_valid = validate(&mut textarea);
loop {
term.draw(|f| {
let chunks = layout.split(f.size());
let widget = textarea.widget();
f.render_widget(widget, chunks[0]);
})?;
match crossterm::event::read()?.into() {
Input { key: Key::Esc, .. } => break,
Input {
key: Key::Enter, ..
} if is_valid => break,
Input {
key: Key::Char('m'),
ctrl: true,
..
}
| Input {
key: Key::Enter, ..
} => {}
input => {
// TextArea::input returns if the input modified its text
if textarea.input(input) {
is_valid = validate(&mut textarea);
}
}
}
}
disable_raw_mode()?;
crossterm::execute!(
term.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
term.show_cursor()?;
println!("Input: {:?}", textarea.lines()[0]);
Ok(())
}