tui-widgets: Add `TextInput` widget

6438963b91fac99e4b24f01ca7a93f48c1c812e0
Alexis Sellier committed ago 1 parent 58ef4a12
crates/tui-widgets/src/input.rs added +390 -0
1 +
//! Editable text input widget.
2 +
//!
3 +
//! [`TextInput`] owns the edited text and caret, exposing granular editing and navigation
4 +
//! operations plus a [`TextInput::input`] helper that maps a [`Key`](rustik_tui_core::Key) to the
5 +
//! matching operation. [`TextField`] renders that state into an area, scrolling to keep the caret
6 +
//! visible and recording the caret's screen position so the caller can place the terminal cursor.
7 +
//!
8 +
//! Columns are measured in characters, so caret placement assumes single-width glyphs; wide
9 +
//! characters shift the rendered caret by one cell each.
10 +
11 +
use rustik_tui_core as tui_core;
12 +
use tui_core::{Buffer, Constraint, Key, Point, Rect, Size, StatefulWidget, Style};
13 +
14 +
/// Editable text buffer with a caret and viewport offsets.
15 +
#[derive(Clone, Debug)]
16 +
pub struct TextInput {
17 +
    /// Edited text, with `\n` separating logical lines.
18 +
    value: String,
19 +
    /// Caret position as a byte offset into [`TextInput::value`].
20 +
    cursor: usize,
21 +
    /// First visible logical line, maintained while rendering.
22 +
    scroll: usize,
23 +
    /// First visible column, maintained while rendering.
24 +
    hscroll: usize,
25 +
    /// Caret screen position recorded by the last render.
26 +
    caret: Point,
27 +
}
28 +
29 +
impl Default for TextInput {
30 +
    fn default() -> Self {
31 +
        Self {
32 +
            value: String::new(),
33 +
            cursor: 0,
34 +
            scroll: 0,
35 +
            hscroll: 0,
36 +
            caret: Point::new(0, 0),
37 +
        }
38 +
    }
39 +
}
40 +
41 +
impl TextInput {
42 +
    /// Creates an empty input with the caret at the start.
43 +
    pub fn new() -> Self {
44 +
        Self::default()
45 +
    }
46 +
47 +
    /// Returns the edited text.
48 +
    pub fn value(&self) -> &str {
49 +
        &self.value
50 +
    }
51 +
52 +
    /// Returns whether the input has no non-whitespace content.
53 +
    pub fn is_empty(&self) -> bool {
54 +
        self.value.trim().is_empty()
55 +
    }
56 +
57 +
    /// Returns the caret screen position recorded by the last render.
58 +
    pub fn caret(&self) -> Point {
59 +
        self.caret
60 +
    }
61 +
62 +
    /// Applies the edit or navigation bound to `key`, returning whether the
63 +
    /// input changed. `Enter`, `Tab`, and other keys are left to the caller so
64 +
    /// it can decide submit and newline semantics.
65 +
    pub fn input(&mut self, key: Key) -> bool {
66 +
        match key {
67 +
            Key::Char(ch) => self.insert(ch),
68 +
            Key::Backspace => self.backspace(),
69 +
            Key::Delete => self.delete(),
70 +
            Key::Left => self.move_left(),
71 +
            Key::Right => self.move_right(),
72 +
            Key::Up => self.move_up(),
73 +
            Key::Down => self.move_down(),
74 +
            Key::Home => self.move_home(),
75 +
            Key::End => self.move_end(),
76 +
            _ => false,
77 +
        }
78 +
    }
79 +
80 +
    /// Inserts `ch` at the caret.
81 +
    pub fn insert(&mut self, ch: char) -> bool {
82 +
        self.value.insert(self.cursor, ch);
83 +
        self.cursor += ch.len_utf8();
84 +
        true
85 +
    }
86 +
87 +
    /// Inserts a line break at the caret.
88 +
    pub fn newline(&mut self) -> bool {
89 +
        self.insert('\n')
90 +
    }
91 +
92 +
    /// Deletes the character before the caret.
93 +
    pub fn backspace(&mut self) -> bool {
94 +
        let Some(ch) = self.value[..self.cursor].chars().next_back() else {
95 +
            return false;
96 +
        };
97 +
        let start = self.cursor - ch.len_utf8();
98 +
        self.value.remove(start);
99 +
        self.cursor = start;
100 +
101 +
        true
102 +
    }
103 +
104 +
    /// Deletes the character at the caret.
105 +
    pub fn delete(&mut self) -> bool {
106 +
        if self.cursor >= self.value.len() {
107 +
            return false;
108 +
        }
109 +
        self.value.remove(self.cursor);
110 +
        true
111 +
    }
112 +
113 +
    /// Moves the caret one character left.
114 +
    pub fn move_left(&mut self) -> bool {
115 +
        let Some(ch) = self.value[..self.cursor].chars().next_back() else {
116 +
            return false;
117 +
        };
118 +
        self.cursor -= ch.len_utf8();
119 +
        true
120 +
    }
121 +
122 +
    /// Moves the caret one character right.
123 +
    pub fn move_right(&mut self) -> bool {
124 +
        let Some(ch) = self.value[self.cursor..].chars().next() else {
125 +
            return false;
126 +
        };
127 +
        self.cursor += ch.len_utf8();
128 +
        true
129 +
    }
130 +
131 +
    /// Moves the caret to the start of the current line.
132 +
    pub fn move_home(&mut self) -> bool {
133 +
        let start = self.value[..self.cursor].rfind('\n').map_or(0, |i| i + 1);
134 +
        if start == self.cursor {
135 +
            return false;
136 +
        }
137 +
        self.cursor = start;
138 +
        true
139 +
    }
140 +
141 +
    /// Moves the caret to the end of the current line.
142 +
    pub fn move_end(&mut self) -> bool {
143 +
        let end = self.value[self.cursor..]
144 +
            .find('\n')
145 +
            .map_or(self.value.len(), |i| self.cursor + i);
146 +
        if end == self.cursor {
147 +
            return false;
148 +
        }
149 +
        self.cursor = end;
150 +
        true
151 +
    }
152 +
153 +
    /// Moves the caret up one line, keeping the column where possible.
154 +
    pub fn move_up(&mut self) -> bool {
155 +
        let (row, col) = self.row_col();
156 +
        if row == 0 {
157 +
            return false;
158 +
        }
159 +
        self.cursor = self.offset_at(row - 1, col);
160 +
        true
161 +
    }
162 +
163 +
    /// Moves the caret down one line, keeping the column where possible.
164 +
    pub fn move_down(&mut self) -> bool {
165 +
        let (row, col) = self.row_col();
166 +
        if row + 1 >= self.lines().count() {
167 +
            return false;
168 +
        }
169 +
        self.cursor = self.offset_at(row + 1, col);
170 +
        true
171 +
    }
172 +
173 +
    /// Returns the logical lines split on `\n`.
174 +
    fn lines(&self) -> impl Iterator<Item = &str> {
175 +
        self.value.split('\n')
176 +
    }
177 +
178 +
    /// Returns the byte range of each logical line, excluding separators.
179 +
    fn line_ranges(&self) -> Vec<(usize, usize)> {
180 +
        let mut ranges = Vec::new();
181 +
        let mut start = 0;
182 +
        for (i, byte) in self.value.bytes().enumerate() {
183 +
            if byte == b'\n' {
184 +
                ranges.push((start, i));
185 +
                start = i + 1;
186 +
            }
187 +
        }
188 +
        ranges.push((start, self.value.len()));
189 +
        ranges
190 +
    }
191 +
192 +
    /// Returns the caret's `(row, column)` in characters.
193 +
    fn row_col(&self) -> (usize, usize) {
194 +
        let before = &self.value[..self.cursor];
195 +
        let row = before.matches('\n').count();
196 +
        let col = before
197 +
            .rsplit('\n')
198 +
            .next()
199 +
            .map_or(0, |line| line.chars().count());
200 +
        (row, col)
201 +
    }
202 +
203 +
    /// Returns the byte offset of `column` on `row`, clamped to the line end.
204 +
    fn offset_at(&self, row: usize, column: usize) -> usize {
205 +
        let ranges = self.line_ranges();
206 +
        let Some(&(start, end)) = ranges.get(row) else {
207 +
            return self.value.len();
208 +
        };
209 +
        let line = &self.value[start..end];
210 +
        let offset = line
211 +
            .char_indices()
212 +
            .nth(column)
213 +
            .map_or(end - start, |(i, _)| i);
214 +
215 +
        start + offset
216 +
    }
217 +
}
218 +
219 +
/// Renders a [`TextInput`] into an area with a visible caret.
220 +
#[derive(Clone, Debug)]
221 +
pub struct TextField {
222 +
    /// Style applied to the edited text.
223 +
    style: Style,
224 +
    /// Placeholder shown when the input is empty.
225 +
    placeholder: Option<String>,
226 +
    /// Style applied to the placeholder text.
227 +
    placeholder_style: Style,
228 +
}
229 +
230 +
impl TextField {
231 +
    /// Creates a text field with default styling and no placeholder.
232 +
    pub fn new() -> Self {
233 +
        Self {
234 +
            style: Style::default(),
235 +
            placeholder: None,
236 +
            placeholder_style: Style::default().dim(),
237 +
        }
238 +
    }
239 +
240 +
    /// Sets the text style.
241 +
    pub fn style(mut self, style: Style) -> Self {
242 +
        self.style = style;
243 +
        self
244 +
    }
245 +
246 +
    /// Sets the placeholder shown while the input is empty.
247 +
    pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
248 +
        self.placeholder = Some(placeholder.into());
249 +
        self
250 +
    }
251 +
252 +
    /// Sets the placeholder style.
253 +
    pub fn placeholder_style(mut self, style: Style) -> Self {
254 +
        self.placeholder_style = style;
255 +
        self
256 +
    }
257 +
}
258 +
259 +
impl Default for TextField {
260 +
    fn default() -> Self {
261 +
        Self::new()
262 +
    }
263 +
}
264 +
265 +
impl StatefulWidget for TextField {
266 +
    type State = TextInput;
267 +
268 +
    fn size(&self, parent: Constraint) -> Size {
269 +
        parent.bounded_size()
270 +
    }
271 +
272 +
    fn render_with_state(&mut self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
273 +
        if area.is_empty() {
274 +
            return;
275 +
        }
276 +
        if state.value.is_empty() {
277 +
            if let Some(placeholder) = &self.placeholder {
278 +
                let text: String = placeholder.chars().take(area.cols).collect();
279 +
                buf.set_str(area.x, area.y, &text, self.placeholder_style);
280 +
            }
281 +
            state.scroll = 0;
282 +
            state.hscroll = 0;
283 +
            state.caret = Point::new(area.x, area.y);
284 +
            return;
285 +
        }
286 +
        let (row, col) = state.row_col();
287 +
288 +
        if row < state.scroll {
289 +
            state.scroll = row;
290 +
        } else if row >= state.scroll + area.rows {
291 +
            state.scroll = row + 1 - area.rows;
292 +
        }
293 +
        if col < state.hscroll {
294 +
            state.hscroll = col;
295 +
        } else if col >= state.hscroll + area.cols {
296 +
            state.hscroll = col + 1 - area.cols;
297 +
        }
298 +
        let ranges = state.line_ranges();
299 +
300 +
        for screen_row in 0..area.rows {
301 +
            let Some(&(start, end)) = ranges.get(state.scroll + screen_row) else {
302 +
                break;
303 +
            };
304 +
            let text: String = state.value[start..end]
305 +
                .chars()
306 +
                .skip(state.hscroll)
307 +
                .take(area.cols)
308 +
                .collect();
309 +
            buf.set_str(area.x, area.y + screen_row, &text, self.style);
310 +
        }
311 +
        state.caret = Point::new(
312 +
            area.x + col.saturating_sub(state.hscroll),
313 +
            area.y + row.saturating_sub(state.scroll),
314 +
        );
315 +
    }
316 +
}
317 +
318 +
#[cfg(test)]
319 +
mod tests {
320 +
    use super::*;
321 +
    use tui_core::Buffer;
322 +
323 +
    #[test]
324 +
    fn typing_and_backspace_track_the_caret() {
325 +
        let mut input = TextInput::new();
326 +
        for ch in "abc".chars() {
327 +
            input.insert(ch);
328 +
        }
329 +
        assert_eq!(input.value(), "abc");
330 +
        assert!(input.backspace());
331 +
        assert_eq!(input.value(), "ab");
332 +
        assert!(input.move_left());
333 +
        assert!(input.insert('X'));
334 +
        assert_eq!(input.value(), "aXb");
335 +
    }
336 +
337 +
    #[test]
338 +
    fn vertical_navigation_keeps_column() {
339 +
        let mut input = TextInput::new();
340 +
        for ch in "ab\ncd\nefgh".chars() {
341 +
            input.input(Key::Char(ch));
342 +
        }
343 +
        input.move_home();
344 +
        for _ in 0..2 {
345 +
            input.move_right();
346 +
        }
347 +
        // Caret is at column 2 on the last line; move up twice to the first.
348 +
        assert!(input.move_up());
349 +
        assert!(input.move_up());
350 +
        assert_eq!(input.row_col(), (0, 2));
351 +
    }
352 +
353 +
    #[test]
354 +
    fn move_up_clamps_to_shorter_line() {
355 +
        let mut input = TextInput::new();
356 +
        for ch in "ab\nlonger".chars() {
357 +
            input.insert(ch);
358 +
        }
359 +
        input.move_end();
360 +
        assert!(input.move_up());
361 +
        assert_eq!(input.row_col(), (0, 2));
362 +
    }
363 +
364 +
    #[test]
365 +
    fn render_places_caret_and_scrolls_to_keep_it_visible() {
366 +
        let mut field = TextField::new();
367 +
        let mut input = TextInput::new();
368 +
        for ch in "one\ntwo\nthree".chars() {
369 +
            input.insert(ch);
370 +
        }
371 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 6, 2));
372 +
373 +
        field.render_with_state(buffer.area(), &mut buffer, &mut input);
374 +
375 +
        // The caret is on the third line; a two-row area scrolls to show it.
376 +
        assert_eq!(buffer.lines(), vec!["two   ", "three "]);
377 +
        assert_eq!(input.caret(), Point::new(5, 1));
378 +
    }
379 +
380 +
    #[test]
381 +
    fn empty_input_renders_placeholder() {
382 +
        let mut field = TextField::new().placeholder("type here");
383 +
        let mut input = TextInput::new();
384 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 9, 1));
385 +
386 +
        field.render_with_state(buffer.area(), &mut buffer, &mut input);
387 +
388 +
        assert_eq!(buffer.lines(), vec!["type here"]);
389 +
    }
390 +
}
crates/tui-widgets/src/lib.rs +3 -0
12 12
13 13
/// One-line action hint bar.
14 14
pub mod action_bar;
15 15
/// Compact text badge widget.
16 16
pub mod badge;
17 +
/// Editable text input widget.
18 +
pub mod input;
17 19
/// Selectable list widget.
18 20
pub mod list;
19 21
/// Centered overlay widget.
20 22
pub mod overlay;
21 23
/// Shared-border multi-panel layout.
29 31
/// Scroll viewport primitives.
30 32
pub mod viewport;
31 33
32 34
pub use action_bar::{ActionBar, ActionItem, ActionList};
33 35
pub use badge::Badge;
36 +
pub use input::{TextField, TextInput};
34 37
pub use list::{List, ListState, Selection};
35 38
pub use overlay::{Overlay, overlay_area};
36 39
pub use panel::Panel;
37 40
pub use scrollbar::{Scrollbar, ScrollbarStyle};
38 41
pub use scrollview::{ScrollLayout, ScrollMetrics, ScrollView, VirtualScrollView, scroll_layout};