ratada 0.2.0

A ratatui widget toolkit: driver, modals, forms, pickers, theming
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! A multi-line text area: wrapped editing with a caret, selection and
//! clipboard. Reuses [`TextCursor`] from the single-line `input` module.
//!
//! The caller handles its own control keys (e.g. `Esc`, `Ctrl+G` for an
//! external editor) before delegating editing keys here.

use std::cell::Cell;

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::{
    Frame,
    layout::Rect,
    style::{Color, Style},
    text::{Line, Span},
    widgets::Paragraph,
};
use unicode_width::UnicodeWidthChar;

use super::{
    chrome,
    input::{self, TextCursor},
    nav, scroll, style,
};
use crate::theme::Skin;

/// A wrapped, editable multi-line text buffer.
#[derive(Default)]
pub struct TextArea {
    text: String,
    cursor: TextCursor,
    width: Cell<usize>,
    scroll: Cell<usize>,
    max_len: Option<usize>,
    decor: Option<chrome::BoxDecor>,
}

impl TextArea {
    /// Creates a multi-line editor pre-filled with `initial`.
    ///
    /// # Examples
    ///
    /// ```
    /// use ratada::textarea::TextArea;
    ///
    /// let area = TextArea::new("line 1\nline 2").max_len(200);
    /// assert_eq!(area.text(), "line 1\nline 2");
    /// ```
    pub fn new(initial: &str) -> Self {
        Self {
            text: initial.to_string(),
            cursor: TextCursor::at_end(initial),
            width: Cell::new(1),
            scroll: Cell::new(0),
            ..Self::default()
        }
    }

    /// Limits the buffer to `max` characters (enforced on typing and paste) and
    /// feeds the badge in the boxed variant.
    #[must_use]
    pub fn max_len(mut self, max: usize) -> Self {
        self.max_len = Some(max);
        self
    }

    /// Draws the area inside a rounded box with the given caption/badge (see
    /// [`chrome::BoxDecor`]); omit it for a plain area.
    #[must_use]
    pub fn boxed(mut self, decor: chrome::BoxDecor) -> Self {
        self.decor = Some(decor);
        self
    }

    /// The current buffer contents.
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Replaces the whole buffer (e.g. after an external editor) and parks the
    /// caret at the end.
    pub fn set_text(&mut self, text: String) {
        self.cursor = TextCursor::at_end(&text);
        self.text = text;
    }

    /// Applies one editing key; returns whether it was consumed.
    pub fn handle_key(&mut self, key: KeyEvent) -> bool {
        let width = self.width.get().max(1);
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let shift = key.modifiers.contains(KeyModifiers::SHIFT);
        let mut chars: Vec<char> = self.text.chars().collect();
        let len = chars.len();
        self.cursor.pos = self.cursor.pos.min(len);

        let consumed = match key.code {
            KeyCode::Left => {
                self.move_to(self.cursor.pos.saturating_sub(1), shift);
                true
            }
            KeyCode::Right => {
                self.move_to((self.cursor.pos + 1).min(len), shift);
                true
            }
            KeyCode::Up => {
                let to = self.vertical(&chars, width, -1);
                self.move_to(to, shift);
                true
            }
            KeyCode::Down => {
                let to = self.vertical(&chars, width, 1);
                self.move_to(to, shift);
                true
            }
            KeyCode::Home => {
                let (start, _) = self.row_bounds(&chars, width);
                self.move_to(start, shift);
                true
            }
            KeyCode::End => {
                let (_, end) = self.row_bounds(&chars, width);
                self.move_to(end, shift);
                true
            }
            KeyCode::Char('a') if ctrl => {
                self.cursor.anchor = Some(0);
                self.cursor.pos = len;
                true
            }
            KeyCode::Char('c') if ctrl => {
                self.copy(&chars);
                true
            }
            KeyCode::Char('x') if ctrl => {
                self.copy(&chars);
                self.delete_selection(&mut chars);
                true
            }
            KeyCode::Char('v') if ctrl => {
                self.paste(&mut chars);
                true
            }
            KeyCode::Enter => {
                self.insert(&mut chars, '\n');
                true
            }
            KeyCode::Backspace => {
                input::backspace(&mut chars, &mut self.cursor);
                true
            }
            KeyCode::Delete => {
                input::delete_forward(&mut chars, &mut self.cursor);
                true
            }
            KeyCode::Char(ch) if !ctrl => {
                self.insert(&mut chars, ch);
                true
            }
            _ => false,
        };

        if consumed {
            self.text = chars.into_iter().collect();
        }
        consumed
    }

    /// Renders the buffer into `area`, scrolling so the caret stays visible and
    /// filling the field with the input background (active tint when `focused`).
    /// A block caret is shown only when `focused`. Wrapped in a box when
    /// decorated via [`Self::boxed`].
    pub fn render(
        &self,
        frame: &mut Frame,
        area: Rect,
        skin: &Skin,
        focused: bool,
    ) {
        let inner = match &self.decor {
            Some(decor) => {
                chrome::framed_decor(frame, area, skin, decor, &self.badge())
            }
            None => area,
        };
        let palette = &skin.palette;
        let base_bg = if focused {
            palette.input_bg_active
        } else {
            palette.input_bg
        };

        let width = inner.width.max(1) as usize;
        let height = inner.height.max(1) as usize;
        self.width.set(width);
        let chars: Vec<char> = self.text.chars().collect();
        let rows = wrap(&chars, width);
        let (caret_row, caret_col) = locate(&rows, self.cursor.pos);

        let scroll = nav::keep_visible(
            nav::ScrollView {
                total: rows.len(),
                offset: self.scroll.get(),
                viewport: height,
            },
            caret_row,
        );
        self.scroll.set(scroll);

        let selection = self.cursor.selection();
        let cursor_style = style::bg(palette.cursor).fg(Color::Black);
        let selection_style = style::bg(palette.selection);

        let lines: Vec<Line> = rows
            .iter()
            .enumerate()
            .skip(scroll)
            .take(height)
            .map(|(row_index, &(start, end))| {
                let mut spans: Vec<Span> = Vec::new();
                for (offset, ch) in chars[start..end].iter().enumerate() {
                    let index = start + offset;
                    let mut cell = Style::default();
                    if let Some((from, to)) = selection
                        && index >= from
                        && index < to
                    {
                        cell = selection_style;
                    }
                    if focused && row_index == caret_row && offset == caret_col
                    {
                        cell = cursor_style;
                    }
                    spans.push(Span::styled(ch.to_string(), cell));
                }
                if focused && row_index == caret_row && caret_col == end - start
                {
                    spans.push(Span::styled(" ".to_string(), cursor_style));
                }
                Line::from(spans)
            })
            .collect();

        // The paragraph's base style fills the whole field (including blank
        // rows) with the input background; spans override per cell.
        frame.render_widget(
            Paragraph::new(lines).style(style::bg(base_bg)),
            inner,
        );
        // A scrollbar on the right whenever the wrapped text overflows.
        scroll::render_scrollbar(
            frame,
            inner,
            skin,
            nav::ScrollView {
                total: rows.len(),
                offset: scroll,
                viewport: height,
            },
        );
    }

    /// The automatic badge text: character count, or `n/max` with a limit.
    fn badge(&self) -> String {
        let count = self.text.chars().count();
        match self.max_len {
            Some(max) => format!("{count}/{max}"),
            None => count.to_string(),
        }
    }

    // The editing primitives below all delegate to the shared `input` core so
    // the single-line edit behaviour has one home (SSOT); only the multi-line
    // navigation (`row_bounds`/`vertical`) and dispatch live here.

    fn move_to(&mut self, pos: usize, extend: bool) {
        input::move_caret(&mut self.cursor, pos, extend);
    }

    fn insert(&mut self, chars: &mut Vec<char>, ch: char) {
        input::insert_char(chars, &mut self.cursor, ch, self.max_len);
    }

    fn delete_selection(&mut self, chars: &mut Vec<char>) -> bool {
        input::delete_selection(chars, &mut self.cursor)
    }

    fn copy(&self, chars: &[char]) {
        input::copy_selection(chars, &self.cursor);
    }

    fn paste(&mut self, chars: &mut Vec<char>) {
        input::paste_multiline(chars, &mut self.cursor, self.max_len);
    }

    fn row_bounds(&self, chars: &[char], width: usize) -> (usize, usize) {
        let rows = wrap(chars, width);
        let (row, _) = locate(&rows, self.cursor.pos);
        rows[row]
    }

    fn vertical(&self, chars: &[char], width: usize, delta: isize) -> usize {
        let rows = wrap(chars, width);
        let (row, col) = locate(&rows, self.cursor.pos);
        let target = (row as isize + delta).clamp(0, rows.len() as isize - 1);
        let (start, end) = rows[target as usize];
        start + col.min(end - start)
    }
}

/// Splits `chars` into display rows of at most `width` columns (measured by
/// [`UnicodeWidthChar`], so wide glyphs count as two), breaking on newlines
/// (which are not included in any row). A single glyph wider than `width` still
/// gets its own row, so the loop always makes progress.
fn wrap(chars: &[char], width: usize) -> Vec<(usize, usize)> {
    let width = width.max(1);
    let mut rows = Vec::new();
    let mut seg_start = 0;
    loop {
        let seg_end = chars[seg_start..]
            .iter()
            .position(|&c| c == '\n')
            .map_or(chars.len(), |offset| seg_start + offset);
        let mut start = seg_start;
        loop {
            let mut end = start;
            let mut used = 0usize;
            while end < seg_end {
                let char_width = chars[end].width().unwrap_or(0);
                if end > start && used + char_width > width {
                    break;
                }
                used += char_width;
                end += 1;
            }
            rows.push((start, end));
            if end >= seg_end {
                break;
            }
            start = end;
        }
        match chars[seg_start..].iter().position(|&c| c == '\n') {
            Some(offset) => seg_start += offset + 1,
            None => break,
        }
    }
    if rows.is_empty() {
        rows.push((0, 0));
    }
    rows
}

/// Maps a caret char index to its `(row, column)` in `rows`.
fn locate(rows: &[(usize, usize)], pos: usize) -> (usize, usize) {
    for (index, &(start, end)) in rows.iter().enumerate() {
        if pos < end {
            return (index, pos - start);
        }
        if pos == end {
            match rows.get(index + 1) {
                // Soft-wrap boundary: caret belongs to the next row's start.
                Some(&(next_start, _)) if next_start == pos => {}
                _ => return (index, pos - start),
            }
        }
    }
    let last = rows.len() - 1;
    (last, pos - rows[last].0)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn wrap_breaks_on_width_and_newlines() {
        let chars: Vec<char> = "abcdef\nxy".chars().collect();
        // width 4: "abcd","ef","xy"
        assert_eq!(wrap(&chars, 4), vec![(0, 4), (4, 6), (7, 9)]);
    }

    #[test]
    fn empty_buffer_has_one_row() {
        assert_eq!(wrap(&[], 4), vec![(0, 0)]);
    }

    #[test]
    fn wrap_measures_display_width_of_wide_chars() {
        // '世'/'界' are width-2; at width 3 only one wide glyph fits per row,
        // then the narrow 'a' joins the second row.
        let chars: Vec<char> = "世界a".chars().collect();
        assert_eq!(wrap(&chars, 3), vec![(0, 1), (1, 3)]);
    }

    #[test]
    fn trailing_newline_adds_empty_row() {
        let chars: Vec<char> = "ab\n".chars().collect();
        assert_eq!(wrap(&chars, 4), vec![(0, 2), (3, 3)]);
    }

    #[test]
    fn enter_inserts_newline() {
        let mut area = TextArea::new("ab");
        area.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
        assert_eq!(area.text(), "ab\n");
    }

    #[test]
    fn max_len_blocks_typing_past_the_limit() {
        let mut area = TextArea::new("ab").max_len(3);
        area.handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::NONE));
        assert_eq!(area.text(), "abc");
        area.handle_key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::NONE));
        assert_eq!(area.text(), "abc");
    }

    #[test]
    fn backspace_delegates_to_the_shared_edit_core() {
        let mut area = TextArea::new("ab");
        area.handle_key(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE));
        assert_eq!(area.text(), "a");
    }

    #[test]
    fn shift_left_selects_and_typing_replaces_via_the_core() {
        let mut area = TextArea::new("abc");
        area.handle_key(KeyEvent::new(KeyCode::Left, KeyModifiers::SHIFT));
        assert_eq!(area.cursor.selection(), Some((2, 3)));
        area.handle_key(KeyEvent::new(KeyCode::Char('X'), KeyModifiers::NONE));
        assert_eq!(area.text(), "abX");
    }

    #[test]
    fn ctrl_a_selects_all_then_backspace_clears() {
        let mut area = TextArea::new("line 1\nline 2");
        area.handle_key(KeyEvent::new(
            KeyCode::Char('a'),
            KeyModifiers::CONTROL,
        ));
        assert_eq!(area.cursor.selection(), Some((0, 13)));
        area.handle_key(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE));
        assert_eq!(area.text(), "");
    }
}