Skip to main content

waxterm/widgets/
text_input.rs

1use ratatui::layout::Rect;
2use ratatui::style::{Color, Style};
3use ratatui::text::{Line, Span};
4use ratatui::widgets::Paragraph;
5use ratatui::Frame;
6
7use crate::input::KeyPress;
8
9use super::WidgetResult;
10
11/// Single-line text input with cursor.
12pub struct TextInput {
13    label: String,
14    value: Vec<u8>,
15    cursor: usize,
16    default: Option<String>,
17}
18
19impl TextInput {
20    pub fn new(label: impl Into<String>) -> Self {
21        Self {
22            label: label.into(),
23            value: Vec::new(),
24            cursor: 0,
25            default: None,
26        }
27    }
28
29    pub fn with_default(mut self, default: impl Into<String>) -> Self {
30        self.default = Some(default.into());
31        self
32    }
33
34    /// Current text value.
35    pub fn value(&self) -> String {
36        if self.value.is_empty() {
37            if let Some(ref d) = self.default {
38                return d.clone();
39            }
40        }
41        String::from_utf8_lossy(&self.value).into_owned()
42    }
43
44    pub fn handle_key(&mut self, key: &KeyPress) -> WidgetResult<String> {
45        match key {
46            KeyPress::Enter => WidgetResult::Confirmed(self.value()),
47            KeyPress::Escape => WidgetResult::Cancelled,
48            KeyPress::Backspace => {
49                if self.cursor > 0 {
50                    self.cursor -= 1;
51                    self.value.remove(self.cursor);
52                }
53                WidgetResult::Pending
54            }
55            KeyPress::ArrowLeft => {
56                if self.cursor > 0 {
57                    self.cursor -= 1;
58                }
59                WidgetResult::Pending
60            }
61            KeyPress::ArrowRight => {
62                if self.cursor < self.value.len() {
63                    self.cursor += 1;
64                }
65                WidgetResult::Pending
66            }
67            KeyPress::Char(b) if b.is_ascii_graphic() || *b == b' ' => {
68                self.value.insert(self.cursor, *b);
69                self.cursor += 1;
70                WidgetResult::Pending
71            }
72            _ => WidgetResult::Pending,
73        }
74    }
75
76    pub fn render(&self, frame: &mut Frame, area: Rect) {
77        let display_val = String::from_utf8_lossy(&self.value);
78
79        let mut spans = vec![
80            Span::styled(&self.label, Style::default().fg(Color::Cyan)),
81            Span::raw(" "),
82        ];
83
84        if self.value.is_empty() {
85            if let Some(ref d) = self.default {
86                spans.push(Span::styled(
87                    format!("({d}) "),
88                    Style::default().fg(Color::DarkGray),
89                ));
90            }
91        }
92
93        // Text before cursor
94        if self.cursor > 0 {
95            let before = &display_val[..self.cursor];
96            spans.push(Span::raw(before.to_string()));
97        }
98
99        // Cursor character
100        let cursor_ch = if self.cursor < display_val.len() {
101            display_val.chars().nth(self.cursor).unwrap_or(' ')
102        } else {
103            ' '
104        };
105        spans.push(Span::styled(
106            cursor_ch.to_string(),
107            Style::default().fg(Color::Black).bg(Color::White),
108        ));
109
110        // Text after cursor
111        if self.cursor < display_val.len() {
112            let after = &display_val[self.cursor + 1..];
113            if !after.is_empty() {
114                spans.push(Span::raw(after.to_string()));
115            }
116        }
117
118        let paragraph = Paragraph::new(Line::from(spans));
119        frame.render_widget(paragraph, area);
120    }
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126
127    #[test]
128    fn test_type_and_confirm() {
129        let mut input = TextInput::new("Name:");
130        assert_eq!(
131            input.handle_key(&KeyPress::Char(b'h')),
132            WidgetResult::Pending
133        );
134        assert_eq!(
135            input.handle_key(&KeyPress::Char(b'i')),
136            WidgetResult::Pending
137        );
138        assert_eq!(
139            input.handle_key(&KeyPress::Enter),
140            WidgetResult::Confirmed("hi".to_string())
141        );
142    }
143
144    #[test]
145    fn test_backspace() {
146        let mut input = TextInput::new(">");
147        input.handle_key(&KeyPress::Char(b'a'));
148        input.handle_key(&KeyPress::Char(b'b'));
149        input.handle_key(&KeyPress::Backspace);
150        assert_eq!(
151            input.handle_key(&KeyPress::Enter),
152            WidgetResult::Confirmed("a".to_string())
153        );
154    }
155
156    #[test]
157    fn test_default_value() {
158        let input = TextInput::new(">").with_default("hello");
159        assert_eq!(input.value(), "hello");
160    }
161
162    #[test]
163    fn test_escape_cancels() {
164        let mut input = TextInput::new(">");
165        input.handle_key(&KeyPress::Char(b'x'));
166        assert_eq!(input.handle_key(&KeyPress::Escape), WidgetResult::Cancelled);
167    }
168
169    #[test]
170    fn test_cursor_movement() {
171        let mut input = TextInput::new(">");
172        input.handle_key(&KeyPress::Char(b'a'));
173        input.handle_key(&KeyPress::Char(b'c'));
174        input.handle_key(&KeyPress::ArrowLeft);
175        input.handle_key(&KeyPress::Char(b'b'));
176        assert_eq!(
177            input.handle_key(&KeyPress::Enter),
178            WidgetResult::Confirmed("abc".to_string())
179        );
180    }
181}