2024-01-24 19:50:18 +00:00
|
|
|
//! # [Ratatui] User Input example
|
|
|
|
//!
|
|
|
|
//! The latest version of this example is available in the [examples] folder in the repository.
|
|
|
|
//!
|
|
|
|
//! Please note that the examples are designed to be run against the `main` branch of the Github
|
|
|
|
//! repository. This means that you may not be able to compile with the latest release version on
|
|
|
|
//! crates.io, or the one that you have installed locally.
|
|
|
|
//!
|
|
|
|
//! See the [examples readme] for more information on finding examples that match the version of the
|
|
|
|
//! library you are using.
|
|
|
|
//!
|
|
|
|
//! [Ratatui]: https://github.com/ratatui-org/ratatui
|
|
|
|
//! [examples]: https://github.com/ratatui-org/ratatui/blob/main/examples
|
|
|
|
//! [examples readme]: https://github.com/ratatui-org/ratatui/blob/main/examples/README.md
|
|
|
|
|
2024-03-02 09:06:53 +00:00
|
|
|
// A simple example demonstrating how to handle user input. This is a bit out of the scope of
|
|
|
|
// the library as it does not provide any input handling out of the box. However, it may helps
|
|
|
|
// some to get started.
|
|
|
|
//
|
|
|
|
// This is a very simple example:
|
|
|
|
// * An input box always focused. Every character you type is registered here.
|
|
|
|
// * An entered character is inserted at the cursor position.
|
|
|
|
// * Pressing Backspace erases the left character before the cursor position
|
|
|
|
// * Pressing Enter pushes the current input in the history of previous messages. **Note: ** as
|
|
|
|
// this is a relatively simple example unicode characters are unsupported and their use will
|
|
|
|
// result in undefined behaviour.
|
|
|
|
//
|
|
|
|
// See also https://github.com/rhysd/tui-textarea and https://github.com/sayanarijit/tui-input/
|
|
|
|
|
2023-06-12 05:07:15 +00:00
|
|
|
use std::{error::Error, io};
|
|
|
|
|
2021-11-01 21:27:46 +00:00
|
|
|
use crossterm::{
|
2023-02-15 21:52:08 +00:00
|
|
|
event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind},
|
2021-11-01 21:27:46 +00:00
|
|
|
execute,
|
|
|
|
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
|
|
|
|
};
|
2024-03-02 09:06:53 +00:00
|
|
|
use ratatui::{
|
|
|
|
prelude::*,
|
2024-05-02 10:09:48 +00:00
|
|
|
widgets::{Block, List, ListItem, Paragraph},
|
2024-03-02 09:06:53 +00:00
|
|
|
};
|
2018-09-23 18:59:51 +00:00
|
|
|
|
2020-01-19 17:41:00 +00:00
|
|
|
enum InputMode {
|
|
|
|
Normal,
|
|
|
|
Editing,
|
|
|
|
}
|
|
|
|
|
2018-09-23 18:59:51 +00:00
|
|
|
/// App holds the state of the application
|
2018-01-27 09:27:26 +00:00
|
|
|
struct App {
|
2018-09-23 18:59:51 +00:00
|
|
|
/// Current value of the input box
|
2018-01-27 09:27:26 +00:00
|
|
|
input: String,
|
2023-07-13 10:41:10 +00:00
|
|
|
/// Position of cursor in the editor area.
|
2024-04-27 05:36:36 +00:00
|
|
|
character_index: usize,
|
2020-01-19 17:41:00 +00:00
|
|
|
/// Current input mode
|
|
|
|
input_mode: InputMode,
|
2018-09-23 18:59:51 +00:00
|
|
|
/// History of recorded messages
|
2018-01-27 09:27:26 +00:00
|
|
|
messages: Vec<String>,
|
|
|
|
}
|
|
|
|
|
2024-03-02 09:06:53 +00:00
|
|
|
impl App {
|
|
|
|
const fn new() -> Self {
|
|
|
|
Self {
|
2018-01-27 09:27:26 +00:00
|
|
|
input: String::new(),
|
2020-01-19 17:41:00 +00:00
|
|
|
input_mode: InputMode::Normal,
|
2018-01-27 09:27:26 +00:00
|
|
|
messages: Vec::new(),
|
2024-04-27 05:36:36 +00:00
|
|
|
character_index: 0,
|
2018-01-27 09:27:26 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-07-13 10:41:10 +00:00
|
|
|
fn move_cursor_left(&mut self) {
|
2024-04-27 05:36:36 +00:00
|
|
|
let cursor_moved_left = self.character_index.saturating_sub(1);
|
|
|
|
self.character_index = self.clamp_cursor(cursor_moved_left);
|
2023-07-13 10:41:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn move_cursor_right(&mut self) {
|
2024-04-27 05:36:36 +00:00
|
|
|
let cursor_moved_right = self.character_index.saturating_add(1);
|
|
|
|
self.character_index = self.clamp_cursor(cursor_moved_right);
|
2023-07-13 10:41:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn enter_char(&mut self, new_char: char) {
|
2024-04-27 05:36:36 +00:00
|
|
|
let index = self.byte_index();
|
|
|
|
self.input.insert(index, new_char);
|
2023-07-13 10:41:10 +00:00
|
|
|
self.move_cursor_right();
|
|
|
|
}
|
|
|
|
|
2024-04-27 05:36:36 +00:00
|
|
|
/// Returns the byte index based on the character position.
|
|
|
|
///
|
|
|
|
/// Since each character in a string can be contain multiple bytes, it's necessary to calculate
|
|
|
|
/// the byte index based on the index of the character.
|
|
|
|
fn byte_index(&mut self) -> usize {
|
|
|
|
self.input
|
|
|
|
.char_indices()
|
|
|
|
.map(|(i, _)| i)
|
|
|
|
.nth(self.character_index)
|
|
|
|
.unwrap_or(self.input.len())
|
|
|
|
}
|
|
|
|
|
2023-07-13 10:41:10 +00:00
|
|
|
fn delete_char(&mut self) {
|
2024-04-27 05:36:36 +00:00
|
|
|
let is_not_cursor_leftmost = self.character_index != 0;
|
2023-07-13 10:41:10 +00:00
|
|
|
if is_not_cursor_leftmost {
|
|
|
|
// Method "remove" is not used on the saved text for deleting the selected char.
|
|
|
|
// Reason: Using remove on String works on bytes instead of the chars.
|
|
|
|
// Using remove would require special care because of char boundaries.
|
|
|
|
|
2024-04-27 05:36:36 +00:00
|
|
|
let current_index = self.character_index;
|
2023-07-13 10:41:10 +00:00
|
|
|
let from_left_to_current_index = current_index - 1;
|
|
|
|
|
|
|
|
// Getting all characters before the selected character.
|
|
|
|
let before_char_to_delete = self.input.chars().take(from_left_to_current_index);
|
|
|
|
// Getting all characters after selected character.
|
|
|
|
let after_char_to_delete = self.input.chars().skip(current_index);
|
|
|
|
|
|
|
|
// Put all characters together except the selected one.
|
|
|
|
// By leaving the selected one out, it is forgotten and therefore deleted.
|
|
|
|
self.input = before_char_to_delete.chain(after_char_to_delete).collect();
|
|
|
|
self.move_cursor_left();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn clamp_cursor(&self, new_cursor_pos: usize) -> usize {
|
2024-04-27 05:36:36 +00:00
|
|
|
new_cursor_pos.clamp(0, self.input.chars().count())
|
2023-07-13 10:41:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn reset_cursor(&mut self) {
|
2024-04-27 05:36:36 +00:00
|
|
|
self.character_index = 0;
|
2023-07-13 10:41:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn submit_message(&mut self) {
|
|
|
|
self.messages.push(self.input.clone());
|
|
|
|
self.input.clear();
|
|
|
|
self.reset_cursor();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-03-13 01:02:51 +00:00
|
|
|
fn main() -> Result<(), Box<dyn Error>> {
|
2021-11-01 21:27:46 +00:00
|
|
|
// setup terminal
|
|
|
|
enable_raw_mode()?;
|
|
|
|
let mut stdout = io::stdout();
|
|
|
|
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
|
|
|
|
let backend = CrosstermBackend::new(stdout);
|
2018-09-23 18:59:51 +00:00
|
|
|
let mut terminal = Terminal::new(backend)?;
|
2018-01-27 09:27:26 +00:00
|
|
|
|
2021-11-01 21:27:46 +00:00
|
|
|
// create app and run it
|
2024-03-02 09:06:53 +00:00
|
|
|
let app = App::new();
|
2021-11-01 21:27:46 +00:00
|
|
|
let res = run_app(&mut terminal, app);
|
2019-12-15 20:38:18 +00:00
|
|
|
|
2021-11-01 21:27:46 +00:00
|
|
|
// restore terminal
|
|
|
|
disable_raw_mode()?;
|
|
|
|
execute!(
|
|
|
|
terminal.backend_mut(),
|
|
|
|
LeaveAlternateScreen,
|
|
|
|
DisableMouseCapture
|
|
|
|
)?;
|
|
|
|
terminal.show_cursor()?;
|
2019-12-15 20:38:18 +00:00
|
|
|
|
2021-11-01 21:27:46 +00:00
|
|
|
if let Err(err) = res {
|
2023-05-22 03:46:02 +00:00
|
|
|
println!("{err:?}");
|
2021-11-01 21:27:46 +00:00
|
|
|
}
|
2020-06-15 20:57:23 +00:00
|
|
|
|
2021-11-01 21:27:46 +00:00
|
|
|
Ok(())
|
|
|
|
}
|
2020-06-15 20:57:23 +00:00
|
|
|
|
2021-11-01 21:27:46 +00:00
|
|
|
fn run_app<B: Backend>(terminal: &mut Terminal<B>, mut app: App) -> io::Result<()> {
|
|
|
|
loop {
|
2021-12-23 17:46:25 +00:00
|
|
|
terminal.draw(|f| ui(f, &app))?;
|
2018-09-23 18:59:51 +00:00
|
|
|
|
2021-11-01 21:27:46 +00:00
|
|
|
if let Event::Key(key) = event::read()? {
|
2020-05-16 22:51:57 +00:00
|
|
|
match app.input_mode {
|
2021-11-01 21:27:46 +00:00
|
|
|
InputMode::Normal => match key.code {
|
|
|
|
KeyCode::Char('e') => {
|
2020-01-19 17:41:00 +00:00
|
|
|
app.input_mode = InputMode::Editing;
|
|
|
|
}
|
2021-11-01 21:27:46 +00:00
|
|
|
KeyCode::Char('q') => {
|
|
|
|
return Ok(());
|
2020-01-19 17:41:00 +00:00
|
|
|
}
|
|
|
|
_ => {}
|
|
|
|
},
|
2023-02-15 21:52:08 +00:00
|
|
|
InputMode::Editing if key.kind == KeyEventKind::Press => match key.code {
|
2023-07-13 10:41:10 +00:00
|
|
|
KeyCode::Enter => app.submit_message(),
|
|
|
|
KeyCode::Char(to_insert) => {
|
|
|
|
app.enter_char(to_insert);
|
2020-01-19 17:41:00 +00:00
|
|
|
}
|
2021-11-01 21:27:46 +00:00
|
|
|
KeyCode::Backspace => {
|
2023-07-13 10:41:10 +00:00
|
|
|
app.delete_char();
|
|
|
|
}
|
|
|
|
KeyCode::Left => {
|
|
|
|
app.move_cursor_left();
|
|
|
|
}
|
|
|
|
KeyCode::Right => {
|
|
|
|
app.move_cursor_right();
|
2020-01-19 17:41:00 +00:00
|
|
|
}
|
2021-11-01 21:27:46 +00:00
|
|
|
KeyCode::Esc => {
|
2020-01-19 17:41:00 +00:00
|
|
|
app.input_mode = InputMode::Normal;
|
|
|
|
}
|
|
|
|
_ => {}
|
|
|
|
},
|
2024-03-02 09:06:53 +00:00
|
|
|
InputMode::Editing => {}
|
2020-05-16 22:51:57 +00:00
|
|
|
}
|
2018-01-27 09:27:26 +00:00
|
|
|
}
|
|
|
|
}
|
2021-11-01 21:27:46 +00:00
|
|
|
}
|
|
|
|
|
2023-09-26 05:30:36 +00:00
|
|
|
fn ui(f: &mut Frame, app: &App) {
|
2024-01-05 15:45:14 +00:00
|
|
|
let vertical = Layout::vertical([
|
|
|
|
Constraint::Length(1),
|
|
|
|
Constraint::Length(3),
|
|
|
|
Constraint::Min(1),
|
|
|
|
]);
|
2024-02-02 04:26:35 +00:00
|
|
|
let [help_area, input_area, messages_area] = vertical.areas(f.size());
|
2021-11-01 21:27:46 +00:00
|
|
|
|
|
|
|
let (msg, style) = match app.input_mode {
|
|
|
|
InputMode::Normal => (
|
|
|
|
vec![
|
2023-07-01 09:14:16 +00:00
|
|
|
"Press ".into(),
|
|
|
|
"q".bold(),
|
2023-07-20 20:00:42 +00:00
|
|
|
" to exit, ".into(),
|
2023-07-01 09:14:16 +00:00
|
|
|
"e".bold(),
|
|
|
|
" to start editing.".bold(),
|
2021-11-01 21:27:46 +00:00
|
|
|
],
|
|
|
|
Style::default().add_modifier(Modifier::RAPID_BLINK),
|
|
|
|
),
|
|
|
|
InputMode::Editing => (
|
|
|
|
vec![
|
2023-07-01 09:14:16 +00:00
|
|
|
"Press ".into(),
|
|
|
|
"Esc".bold(),
|
|
|
|
" to stop editing, ".into(),
|
|
|
|
"Enter".bold(),
|
|
|
|
" to record the message".into(),
|
2021-11-01 21:27:46 +00:00
|
|
|
],
|
|
|
|
Style::default(),
|
|
|
|
),
|
|
|
|
};
|
2024-01-07 11:58:13 +00:00
|
|
|
let text = Text::from(Line::from(msg)).patch_style(style);
|
2021-11-01 21:27:46 +00:00
|
|
|
let help_message = Paragraph::new(text);
|
2024-01-05 15:45:14 +00:00
|
|
|
f.render_widget(help_message, help_area);
|
2021-11-01 21:27:46 +00:00
|
|
|
|
2023-05-09 17:59:24 +00:00
|
|
|
let input = Paragraph::new(app.input.as_str())
|
2021-11-01 21:27:46 +00:00
|
|
|
.style(match app.input_mode {
|
|
|
|
InputMode::Normal => Style::default(),
|
|
|
|
InputMode::Editing => Style::default().fg(Color::Yellow),
|
|
|
|
})
|
2024-05-02 10:09:48 +00:00
|
|
|
.block(Block::bordered().title("Input"));
|
2024-01-05 15:45:14 +00:00
|
|
|
f.render_widget(input, input_area);
|
2021-11-01 21:27:46 +00:00
|
|
|
match app.input_mode {
|
|
|
|
InputMode::Normal =>
|
|
|
|
// Hide the cursor. `Frame` does this by default, so we don't need to do anything here
|
|
|
|
{}
|
|
|
|
|
|
|
|
InputMode::Editing => {
|
2023-06-04 10:34:05 +00:00
|
|
|
// Make the cursor visible and ask ratatui to put it at the specified coordinates after
|
|
|
|
// rendering
|
2024-03-02 09:06:53 +00:00
|
|
|
#[allow(clippy::cast_possible_truncation)]
|
2021-11-01 21:27:46 +00:00
|
|
|
f.set_cursor(
|
2023-07-13 10:41:10 +00:00
|
|
|
// Draw the cursor at the current position in the input field.
|
|
|
|
// This position is can be controlled via the left and right arrow key
|
2024-04-27 05:36:36 +00:00
|
|
|
input_area.x + app.character_index as u16 + 1,
|
2021-11-01 21:27:46 +00:00
|
|
|
// Move one line down, from the border to the input line
|
2024-01-05 15:45:14 +00:00
|
|
|
input_area.y + 1,
|
2024-03-02 09:06:53 +00:00
|
|
|
);
|
2021-11-01 21:27:46 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let messages: Vec<ListItem> = app
|
|
|
|
.messages
|
|
|
|
.iter()
|
|
|
|
.enumerate()
|
|
|
|
.map(|(i, m)| {
|
2023-05-22 03:46:02 +00:00
|
|
|
let content = Line::from(Span::raw(format!("{i}: {m}")));
|
2021-11-01 21:27:46 +00:00
|
|
|
ListItem::new(content)
|
|
|
|
})
|
|
|
|
.collect();
|
2024-05-02 10:09:48 +00:00
|
|
|
let messages = List::new(messages).block(Block::bordered().title("Messages"));
|
2024-01-05 15:45:14 +00:00
|
|
|
f.render_widget(messages, messages_area);
|
2018-01-27 09:27:26 +00:00
|
|
|
}
|