From e393c3f90a1459c2ec66bb1ee260afd2ff284530 Mon Sep 17 00:00:00 2001 From: rhysd Date: Thu, 9 Jun 2022 00:01:37 +0900 Subject: [PATCH] implement conversion from crossterm event to textarea input --- examples/minimal.rs | 17 ++++------------- src/lib.rs | 45 ++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 48 insertions(+), 14 deletions(-) diff --git a/examples/minimal.rs b/examples/minimal.rs index f938a8b..a3a13b2 100644 --- a/examples/minimal.rs +++ b/examples/minimal.rs @@ -7,7 +7,7 @@ use tui::backend::CrosstermBackend; use tui::layout::{Constraint, Direction, Layout}; use tui::widgets::{Block, Borders}; use tui::Terminal; -use tui_textarea::{Input, Key, TextArea}; +use tui_textarea::{Input, TextArea}; fn main() -> io::Result<()> { let stdout = io::stdout(); @@ -29,20 +29,11 @@ fn main() -> io::Result<()> { let widget = textarea.widget(); f.render_widget(widget, chunks[0]); })?; - if let Event::Key(key) = crossterm::event::read()? { - match key.code { - KeyCode::Char(c) => textarea.input(Input { - key: Key::Char(c), - ctrl: false, - }), - KeyCode::Backspace => textarea.input(Input { - key: Key::Backspace, - ctrl: false, - }), - KeyCode::Esc => break, - _ => {} + if key.code == KeyCode::Esc { + break; } + textarea.input(Input::from(key)); } } diff --git a/src/lib.rs b/src/lib.rs index da0306c..98a0123 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -14,6 +14,7 @@ pub enum Key { Delete, Home, End, + Null, } pub struct Input { @@ -21,6 +22,47 @@ pub struct Input { pub ctrl: bool, } +impl Default for Input { + fn default() -> Self { + Input { + key: Key::Null, + ctrl: false, + } + } +} + +impl From for Input { + fn from(event: crossterm::event::Event) -> Self { + if let crossterm::event::Event::Key(key) = event { + Self::from(key) + } else { + Self::default() + } + } +} + +impl From for Input { + fn from(key: crossterm::event::KeyEvent) -> Self { + use crossterm::event::{KeyCode, KeyModifiers}; + let ctrl = key.modifiers.contains(KeyModifiers::CONTROL); + let key = match key.code { + KeyCode::Char(c) => Key::Char(c), + KeyCode::Backspace => Key::Backspace, + KeyCode::Enter => Key::Enter, + KeyCode::Left => Key::Left, + KeyCode::Right => Key::Right, + KeyCode::Up => Key::Up, + KeyCode::Down => Key::Down, + KeyCode::Tab => Key::Tab, + KeyCode::Delete => Key::Delete, + KeyCode::Home => Key::Home, + KeyCode::End => Key::End, + _ => Key::Null, + }; + Self { key, ctrl } + } +} + pub struct TextArea<'a> { lines: Vec, block: Option>, @@ -40,7 +82,8 @@ impl<'a> Default for TextArea<'a> { } impl<'a> TextArea<'a> { - pub fn input(&mut self, input: Input) { + pub fn input(&mut self, input: impl Into) { + let input = input.into(); if input.ctrl { // TODO } else {