crates/tui-widgets/src/input.rs 13.3 KiB raw
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, RenderResult, 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
    /// Creates an input initialized with `value`.
48
    pub fn with_value(value: String) -> Self {
49
        let cursor = value.len();
50
        Self {
51
            value,
52
            cursor,
53
            scroll: 0,
54
            hscroll: 0,
55
            caret: Point::new(0, 0),
56
        }
57
    }
58
59
    /// Returns the edited text.
60
    pub fn value(&self) -> &str {
61
        &self.value
62
    }
63
64
    /// Returns whether the input has no non-whitespace content.
65
    pub fn is_empty(&self) -> bool {
66
        self.value.trim().is_empty()
67
    }
68
69
    /// Returns the caret screen position recorded by the last render.
70
    pub fn caret(&self) -> Point {
71
        self.caret
72
    }
73
74
    /// Applies the edit or navigation bound to `key`.
75
    ///
76
    /// Returns whether the buffer or caret changed. `Enter`, `Tab`, and other
77
    /// keys are left to the caller so it can decide submit, focus, and newline
78
    /// semantics for its own mode.
79
    pub fn input(&mut self, key: Key) -> bool {
80
        match key {
81
            Key::Char(ch) => self.insert(ch),
82
            Key::Backspace => self.backspace(),
83
            Key::Delete => self.delete(),
84
            Key::Left => self.move_left(),
85
            Key::Right => self.move_right(),
86
            Key::Up => self.move_up(),
87
            Key::Down => self.move_down(),
88
            Key::Home => self.move_home(),
89
            Key::End => self.move_end(),
90
            _ => false,
91
        }
92
    }
93
94
    /// Inserts `ch` at the caret.
95
    ///
96
    /// The caret is stored as a byte offset, so movement after insertion uses
97
    /// the UTF-8 width of the inserted character.
98
    pub fn insert(&mut self, ch: char) -> bool {
99
        self.value.insert(self.cursor, ch);
100
        self.cursor += ch.len_utf8();
101
        true
102
    }
103
104
    /// Inserts a line break at the caret.
105
    pub fn newline(&mut self) -> bool {
106
        self.insert('\n')
107
    }
108
109
    /// Deletes the character before the caret.
110
    pub fn backspace(&mut self) -> bool {
111
        let Some(ch) = self.value[..self.cursor].chars().next_back() else {
112
            return false;
113
        };
114
        let start = self.cursor - ch.len_utf8();
115
        self.value.remove(start);
116
        self.cursor = start;
117
118
        true
119
    }
120
121
    /// Deletes the character at the caret.
122
    pub fn delete(&mut self) -> bool {
123
        if self.cursor >= self.value.len() {
124
            return false;
125
        }
126
        self.value.remove(self.cursor);
127
        true
128
    }
129
130
    /// Moves the caret one character left.
131
    pub fn move_left(&mut self) -> bool {
132
        let Some(ch) = self.value[..self.cursor].chars().next_back() else {
133
            return false;
134
        };
135
        self.cursor -= ch.len_utf8();
136
        true
137
    }
138
139
    /// Moves the caret one character right.
140
    pub fn move_right(&mut self) -> bool {
141
        let Some(ch) = self.value[self.cursor..].chars().next() else {
142
            return false;
143
        };
144
        self.cursor += ch.len_utf8();
145
        true
146
    }
147
148
    /// Moves the caret to the start of the current line.
149
    pub fn move_home(&mut self) -> bool {
150
        let start = self.value[..self.cursor].rfind('\n').map_or(0, |i| i + 1);
151
        if start == self.cursor {
152
            return false;
153
        }
154
        self.cursor = start;
155
        true
156
    }
157
158
    /// Moves the caret to the end of the current line.
159
    pub fn move_end(&mut self) -> bool {
160
        let end = self.value[self.cursor..]
161
            .find('\n')
162
            .map_or(self.value.len(), |i| self.cursor + i);
163
        if end == self.cursor {
164
            return false;
165
        }
166
        self.cursor = end;
167
        true
168
    }
169
170
    /// Moves the caret up one line, keeping the column where possible.
171
    ///
172
    /// Columns are counted in `char`s and then translated back to a byte offset
173
    /// on the target line. Moving to a shorter line clamps at that line's end.
174
    pub fn move_up(&mut self) -> bool {
175
        let (row, col) = self.row_col();
176
        if row == 0 {
177
            return false;
178
        }
179
        self.cursor = self.offset_at(row - 1, col);
180
        true
181
    }
182
183
    /// Moves the caret down one line, keeping the column where possible.
184
    ///
185
    /// Columns are counted in `char`s and then translated back to a byte offset
186
    /// on the target line. Moving to a shorter line clamps at that line's end.
187
    pub fn move_down(&mut self) -> bool {
188
        let (row, col) = self.row_col();
189
        if row + 1 >= self.lines().count() {
190
            return false;
191
        }
192
        self.cursor = self.offset_at(row + 1, col);
193
        true
194
    }
195
196
    /// Returns the logical lines split on `\n`.
197
    fn lines(&self) -> impl Iterator<Item = &str> {
198
        self.value.split('\n')
199
    }
200
201
    /// Returns the byte range of each logical line, excluding separators.
202
    fn line_ranges(&self) -> Vec<(usize, usize)> {
203
        let mut ranges = Vec::new();
204
        let mut start = 0;
205
        for (i, byte) in self.value.bytes().enumerate() {
206
            if byte == b'\n' {
207
                ranges.push((start, i));
208
                start = i + 1;
209
            }
210
        }
211
        ranges.push((start, self.value.len()));
212
        ranges
213
    }
214
215
    /// Returns the caret's `(row, column)` in characters.
216
    fn row_col(&self) -> (usize, usize) {
217
        let before = &self.value[..self.cursor];
218
        let row = before.matches('\n').count();
219
        let col = before
220
            .rsplit('\n')
221
            .next()
222
            .map_or(0, |line| line.chars().count());
223
        (row, col)
224
    }
225
226
    /// Returns the byte offset of `column` on `row`, clamped to the line end.
227
    ///
228
    /// `column` is a character column, not a byte index. This keeps the stored
229
    /// cursor on a UTF-8 boundary even when the edited text contains non-ASCII
230
    /// characters.
231
    fn offset_at(&self, row: usize, column: usize) -> usize {
232
        let ranges = self.line_ranges();
233
        let Some(&(start, end)) = ranges.get(row) else {
234
            return self.value.len();
235
        };
236
        let line = &self.value[start..end];
237
        let offset = line
238
            .char_indices()
239
            .nth(column)
240
            .map_or(end - start, |(i, _)| i);
241
242
        start + offset
243
    }
244
}
245
246
/// Renders a [`TextInput`] into an area with a visible caret.
247
#[derive(Clone, Debug)]
248
pub struct TextField {
249
    /// Style applied to the edited text.
250
    style: Style,
251
    /// Placeholder shown when the input is empty.
252
    placeholder: Option<String>,
253
    /// Style applied to the placeholder text.
254
    placeholder_style: Style,
255
}
256
257
impl TextField {
258
    /// Creates a text field with default styling and no placeholder.
259
    pub fn new() -> Self {
260
        Self {
261
            style: Style::default(),
262
            placeholder: None,
263
            placeholder_style: Style::default().dim(),
264
        }
265
    }
266
267
    /// Sets the text style.
268
    pub fn style(mut self, style: Style) -> Self {
269
        self.style = style;
270
        self
271
    }
272
273
    /// Sets the placeholder shown while the input is empty.
274
    pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
275
        self.placeholder = Some(placeholder.into());
276
        self
277
    }
278
279
    /// Sets the placeholder style.
280
    pub fn placeholder_style(mut self, style: Style) -> Self {
281
        self.placeholder_style = style;
282
        self
283
    }
284
}
285
286
impl Default for TextField {
287
    fn default() -> Self {
288
        Self::new()
289
    }
290
}
291
292
impl StatefulWidget for TextField {
293
    type State = TextInput;
294
295
    fn size(&self, parent: Constraint) -> Size {
296
        parent.bounded_size()
297
    }
298
299
    fn render_with_state(
300
        &mut self,
301
        area: Rect,
302
        buf: &mut Buffer,
303
        state: &mut Self::State,
304
    ) -> RenderResult {
305
        if area.is_empty() {
306
            return RenderResult::default();
307
        }
308
        if state.value.is_empty() {
309
            if let Some(placeholder) = &self.placeholder {
310
                let text: String = placeholder.chars().take(area.cols).collect();
311
                buf.set_str(area.x, area.y, &text, self.placeholder_style);
312
            }
313
            state.scroll = 0;
314
            state.hscroll = 0;
315
            state.caret = Point::new(area.x, area.y);
316
            return RenderResult {
317
                cursor: Some(state.caret()),
318
            };
319
        }
320
        let (row, col) = state.row_col();
321
        if row < state.scroll {
322
            state.scroll = row;
323
        } else if row >= state.scroll + area.rows {
324
            state.scroll = row + 1 - area.rows;
325
        }
326
        if col < state.hscroll {
327
            state.hscroll = col;
328
        } else if col >= state.hscroll + area.cols {
329
            state.hscroll = col + 1 - area.cols;
330
        }
331
        let ranges = state.line_ranges();
332
333
        for screen_row in 0..area.rows {
334
            let Some(&(start, end)) = ranges.get(state.scroll + screen_row) else {
335
                break;
336
            };
337
            // Horizontal scrolling is also character-based to match caret
338
            // movement. Wide glyphs are documented as an approximation.
339
            let text: String = state.value[start..end]
340
                .chars()
341
                .skip(state.hscroll)
342
                .take(area.cols)
343
                .collect();
344
            buf.set_str(area.x, area.y + screen_row, &text, self.style);
345
        }
346
        state.caret = Point::new(
347
            area.x + col.saturating_sub(state.hscroll),
348
            area.y + row.saturating_sub(state.scroll),
349
        );
350
        RenderResult {
351
            cursor: Some(state.caret()),
352
        }
353
    }
354
}
355
356
#[cfg(test)]
357
mod tests {
358
    use super::*;
359
    use tui_core::Buffer;
360
361
    #[test]
362
    fn typing_and_backspace_track_the_caret() {
363
        let mut input = TextInput::new();
364
        for ch in "abc".chars() {
365
            input.insert(ch);
366
        }
367
        assert_eq!(input.value(), "abc");
368
        assert!(input.backspace());
369
        assert_eq!(input.value(), "ab");
370
        assert!(input.move_left());
371
        assert!(input.insert('X'));
372
        assert_eq!(input.value(), "aXb");
373
    }
374
375
    #[test]
376
    fn vertical_navigation_keeps_column() {
377
        let mut input = TextInput::new();
378
        for ch in "ab\ncd\nefgh".chars() {
379
            input.input(Key::Char(ch));
380
        }
381
        input.move_home();
382
        for _ in 0..2 {
383
            input.move_right();
384
        }
385
        // Caret is at column 2 on the last line; move up twice to the first.
386
        assert!(input.move_up());
387
        assert!(input.move_up());
388
        assert_eq!(input.row_col(), (0, 2));
389
    }
390
391
    #[test]
392
    fn move_up_clamps_to_shorter_line() {
393
        let mut input = TextInput::new();
394
        for ch in "ab\nlonger".chars() {
395
            input.insert(ch);
396
        }
397
        input.move_end();
398
        assert!(input.move_up());
399
        assert_eq!(input.row_col(), (0, 2));
400
    }
401
402
    #[test]
403
    fn render_places_caret_and_scrolls_to_keep_it_visible() {
404
        let mut field = TextField::new();
405
        let mut input = TextInput::new();
406
        for ch in "one\ntwo\nthree".chars() {
407
            input.insert(ch);
408
        }
409
        let mut buffer = Buffer::empty(Rect::new(0, 0, 6, 2));
410
411
        field.render_with_state(buffer.area(), &mut buffer, &mut input);
412
413
        // The caret is on the third line; a two-row area scrolls to show it.
414
        assert_eq!(buffer.lines(), vec!["two   ", "three "]);
415
        assert_eq!(input.caret(), Point::new(5, 1));
416
    }
417
418
    #[test]
419
    fn with_value_places_caret_after_initial_text() {
420
        let mut input = TextInput::with_value("abc".to_owned());
421
        let mut buffer = Buffer::empty(Rect::new(0, 0, 8, 1));
422
423
        TextField::new().render_with_state(buffer.area(), &mut buffer, &mut input);
424
425
        assert_eq!(input.value(), "abc");
426
        assert_eq!(input.caret(), Point::new(3, 0));
427
    }
428
429
    #[test]
430
    fn empty_input_renders_placeholder() {
431
        let mut field = TextField::new().placeholder("type here");
432
        let mut input = TextInput::new();
433
        let mut buffer = Buffer::empty(Rect::new(0, 0, 9, 1));
434
435
        field.render_with_state(buffer.area(), &mut buffer, &mut input);
436
437
        assert_eq!(buffer.lines(), vec!["type here"]);
438
    }
439
}