Skip to main content

text_input/
text_input.rs

1use tv::{Attr, Color, Key, Screen};
2
3fn main() -> tv::Result<()> {
4    let mut scr = Screen::init()?;
5    scr.set_cursor_style(5)?; // blinking bar
6    scr.cursor_visible(true)?;
7
8    let mut input = String::new();
9    let mut cursor = 0usize;
10    let label = "Name: ";
11
12    loop {
13        scr.clear()?;
14
15        // Title
16        scr.set_foreground(Color::rgb(139, 233, 253))?;
17        scr.add_attribute(Attr::BOLD)?;
18        scr.move_print(1, 2, "Text Input Example")?;
19        scr.remove_attribute(Attr::BOLD)?;
20
21        // Label
22        scr.set_foreground(Color::rgb(98, 114, 164))?;
23        scr.move_print(3, 2, label)?;
24
25        // Input text
26        scr.set_foreground(Color::rgb(248, 248, 242))?;
27        scr.print(&input)?;
28
29        // Position cursor inside the input
30        scr.move_cursor(3, (2 + label.len() + cursor) as u16)?;
31
32        // Hint
33        scr.set_foreground(Color::rgb(98, 114, 164))?;
34        scr.move_print(5, 2, "Type text, use ←/→ to move, Ctrl+Q to quit")?;
35
36        // Preview
37        if !input.is_empty() {
38            scr.set_foreground(Color::rgb(80, 250, 123))?;
39            scr.move_print(7, 2, &format!("Hello, {}!", input))?;
40        }
41
42        let key = scr.get_char()?;
43        match key {
44            Key::Ctrl('q') => break,
45            Key::Char(ch) => {
46                input.insert(cursor, ch);
47                cursor += 1;
48            }
49            Key::Backspace => {
50                if cursor > 0 {
51                    cursor -= 1;
52                    input.remove(cursor);
53                }
54            }
55            Key::Delete => {
56                if cursor < input.len() {
57                    input.remove(cursor);
58                }
59            }
60            Key::Left => {
61                if cursor > 0 {
62                    cursor -= 1;
63                }
64            }
65            Key::Right => {
66                if cursor < input.len() {
67                    cursor += 1;
68                }
69            }
70            Key::Home => cursor = 0,
71            Key::End => cursor = input.len(),
72            _ => {}
73        }
74    }
75
76    scr.set_cursor_style(0)?;
77    scr.endwin()?;
78    Ok(())
79}