From 3ba3a559ca3654739d406729c394822492a05e90 Mon Sep 17 00:00:00 2001 From: rhysd Date: Sat, 18 Jun 2022 15:52:31 +0900 Subject: [PATCH] add an example for simple textarea with variable height --- Cargo.toml | 4 ++++ README.md | 1 + examples/variable.rs | 54 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+) create mode 100644 examples/variable.rs diff --git a/Cargo.toml b/Cargo.toml index 0ddc75d..e028d8c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,3 +32,7 @@ required-features = ["crossterm"] [[example]] name = "single_line" required-features = ["crossterm"] + +[[example]] +name = "variable" +required-features = ["crossterm"] diff --git a/README.md b/README.md index 13c5a2d..edb84a8 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,7 @@ cargo run --example minimal - [termion](./examples/termion.rs): Minimal usage with [termion][] support - [multi](./examples/multi.rs): Two split textareas in a screen and switch them - [single_line](./examples/single_line.rs): Single line input form with float number validation +- [variable](./examples/variable.rs): Simple textarea with variable height following the number of lines - [editor](./examples/editor.rs): Simple text editor to edit multiple files ## Minimal Usage diff --git a/examples/variable.rs b/examples/variable.rs new file mode 100644 index 0000000..5c37983 --- /dev/null +++ b/examples/variable.rs @@ -0,0 +1,54 @@ +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::widgets::{Block, Borders}; +use tui::Terminal; +use tui_textarea::{Input, Key, TextArea}; + +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_block( + Block::default() + .borders(Borders::ALL) + .title("Textarea with Variable Height"), + ); + + loop { + term.draw(|f| { + let len = textarea.lines().len() as u16 + 2; // + 2 for borders + let chunks = Layout::default() + .constraints([Constraint::Length(len), Constraint::Min(1)].as_slice()) + .split(f.size()); + f.render_widget(textarea.widget(), chunks[0]); + })?; + match Input::from(crossterm::event::read()?) { + Input { key: Key::Esc, .. } => break, + input => { + textarea.input(input); + } + } + } + + disable_raw_mode()?; + crossterm::execute!( + term.backend_mut(), + LeaveAlternateScreen, + DisableMouseCapture + )?; + term.show_cursor()?; + + println!("Lines: {:?}", textarea.lines()); + Ok(()) +}