rs-rich-interact 0.0.2

Interactive terminal components for rs-rich: event loop, viewport, item model, headless testing
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
//! A multi-line editor (#493, `rich write`).
//!
//! Enter starts a new line; Ctrl+D (or the key the caller chooses) submits
//! and Escape cancels. Lines longer than the space wrap, and the text
//! scrolls to keep the caret in view. The arrows, Home/End, Ctrl+A/E,
//! Ctrl+U/K/W, Backspace and Delete edit as in [`Input`](crate::Input), the
//! caret moving by grapheme cluster; Up and Down move between lines. A
//! character limit counts grapheme clusters, line breaks too. Pasted text
//! keeps its line breaks and tabs (a tab shows as [`TAB`] spaces); other
//! terminal controls are dropped.

use std::cell::Cell;

use rich::cells::split_graphemes;
use rich::Segment;

use crate::component::{Component, Context, Flow, View};
use crate::components::{fit, plain, question, text, Theme};
use crate::event::{Event, Key, KeyCode};
use crate::keymap::{keys, Keymap};
use crate::policy::{LineIo, NotInteractive};

/// The cells a tab takes on screen.
const TAB: usize = 4;

/// The grapheme clusters of `line` as (start, end, cells): rich's, with a
/// tab one of its own, [`TAB`] cells wide, rather than joined to the one
/// before it as a zero-width character is.
fn graphemes(line: &str) -> Vec<(usize, usize, usize)> {
    let mut out = Vec::new();
    let mut start = 0;
    for piece in line.split('\t') {
        let (spans, _) = split_graphemes(piece);
        out.extend(spans.into_iter().map(|(s, e, w)| (start + s, start + e, w)));
        start += piece.len();
        if start < line.len() {
            out.push((start, start + 1, TAB));
            start += 1;
        }
    }
    out
}

/// The cells `text` (one line) takes on screen.
fn cells(text: &str) -> usize {
    graphemes(text).iter().map(|(_, _, width)| width).sum()
}

/// The characters in `text` as the limit counts them: grapheme clusters,
/// and a line break one.
fn length(text: &str) -> usize {
    text.split('\n')
        .map(|line| graphemes(line).len())
        .sum::<usize>()
        + text.matches('\n').count()
}

/// One row on screen: a piece of a line.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Row {
    line: usize,
    /// Byte range of the line's text.
    start: usize,
    end: usize,
    /// Whether it is the line's first row (the one numbered).
    first: bool,
}

/// Multi-line text. Returns the text, lines joined with `\n`.
pub struct TextArea {
    prompt: String,
    lines: Vec<String>,
    /// The caret: a line, and a byte offset into it on a grapheme boundary.
    line: usize,
    at: usize,
    placeholder: Option<String>,
    limit: Option<usize>,
    submit: Key,
    height: usize,
    line_numbers: bool,
    theme: Theme,
    /// The first row shown. Moved in `handle`, which knows the width, and
    /// read in `render`.
    top: Cell<usize>,
    answer: Option<Option<String>>,
}

impl TextArea {
    pub fn new(prompt: impl Into<String>) -> TextArea {
        TextArea {
            prompt: prompt.into(),
            lines: vec![String::new()],
            line: 0,
            at: 0,
            placeholder: None,
            limit: None,
            submit: Key::ctrl('d'),
            height: 5,
            line_numbers: false,
            theme: Theme::default(),
            top: Cell::new(0),
            answer: None,
        }
    }

    /// Start with this text, the caret at its end.
    pub fn value(mut self, value: impl AsRef<str>) -> Self {
        let mut value = clean(value.as_ref());
        if let Some(limit) = self.limit {
            value = TextArea::truncate(&value, limit).to_string();
        }
        self.lines = value.split('\n').map(str::to_string).collect();
        self.line = self.lines.len() - 1;
        self.at = self.lines[self.line].len();
        self
    }

    /// Dim text shown while the area is empty.
    pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
        self.placeholder = Some(placeholder.into());
        self
    }

    /// At most `chars` characters (grapheme clusters, so `👨‍👩‍👧` or `e`
    /// and a combining accent is one), line breaks included. Text already
    /// there beyond it is cut.
    pub fn char_limit(mut self, chars: usize) -> Self {
        self.limit = Some(chars);
        let text = TextArea::truncate(&self.text(), chars).to_string();
        self.value(text)
    }

    /// The first `chars` characters of `text` as the character limit
    /// counts them: grapheme clusters, a line break one. Never cuts a
    /// cluster.
    pub fn truncate(text: &str, chars: usize) -> &str {
        let mut left = chars;
        let mut start = 0;
        for line in text.split('\n') {
            let clusters = graphemes(line);
            if clusters.len() > left {
                return &text[..start + clusters[left].0];
            }
            left -= clusters.len();
            start += line.len();
            if start == text.len() || left == 0 {
                return &text[..start];
            }
            // The line break.
            left -= 1;
            start += 1;
        }
        text
    }

    /// The key that submits (default Ctrl+D).
    pub fn submit_key(mut self, key: Key) -> Self {
        self.submit = key;
        self
    }

    /// Rows of text shown (default 5).
    pub fn height(mut self, rows: usize) -> Self {
        self.height = rows.max(1);
        self
    }

    /// Number the lines.
    pub fn line_numbers(mut self, on: bool) -> Self {
        self.line_numbers = on;
        self
    }

    pub fn theme(mut self, theme: Theme) -> Self {
        self.theme = theme;
        self
    }

    /// The text so far.
    pub fn text(&self) -> String {
        self.lines.join("\n")
    }

    /// The caret: (line, character column).
    pub fn caret(&self) -> (usize, usize) {
        (self.line, self.lines[self.line][..self.at].chars().count())
    }

    fn count(&self) -> usize {
        self.lines
            .iter()
            .map(|line| graphemes(line).len())
            .sum::<usize>()
            + self.lines.len()
            - 1
    }

    /// Rows of text shown in a space `rows` high: the height asked for, cut
    /// to what fits beside the question and the hint.
    fn shown_rows(&self, rows: usize) -> usize {
        self.height.min(rows.saturating_sub(2)).max(1)
    }

    /// Byte offsets where the caret may stop in `line`: grapheme starts and
    /// the end.
    fn stops(line: &str) -> Vec<usize> {
        let mut stops: Vec<usize> = graphemes(line).iter().map(|(start, _, _)| *start).collect();
        stops.push(line.len());
        stops
    }

    /// Insert `text` at the caret, as much of it as the limit leaves room
    /// for. Clusters are counted once in place, since text joins the one
    /// before or after the caret (a combining accent) or splits it.
    fn insert(&mut self, text: &str) {
        let Some(limit) = self.limit else {
            self.splice(text);
            return;
        };
        let room = limit.saturating_sub(self.count());
        // Joining merges at most one cluster at each end.
        let mut text = TextArea::truncate(text, room.saturating_add(2));
        while !text.is_empty() {
            let (line, at, before) = (self.line, self.at, self.lines[self.line].clone());
            let added = self.splice(text);
            if self.count() <= limit {
                return;
            }
            self.lines.drain(line + 1..=line + added);
            self.lines[line] = before;
            (self.line, self.at) = (line, at);
            text = TextArea::truncate(text, length(text) - 1);
        }
    }

    /// Insert `text` at the caret; the number of lines it added.
    fn splice(&mut self, text: &str) -> usize {
        if text.is_empty() {
            return 0;
        }
        let rest = self.lines[self.line].split_off(self.at);
        let mut pieces = text.split('\n');
        let first = pieces.next().unwrap_or("");
        self.lines[self.line].push_str(first);
        let mut line = self.line;
        for piece in pieces {
            line += 1;
            self.lines.insert(line, piece.to_string());
        }
        let added = line - self.line;
        self.line = line;
        self.at = self.lines[line].len();
        self.lines[line].push_str(&rest);
        added
    }

    fn backspace(&mut self) {
        if self.at == 0 {
            if self.line > 0 {
                let line = self.lines.remove(self.line);
                self.line -= 1;
                self.at = self.lines[self.line].len();
                self.lines[self.line].push_str(&line);
            }
            return;
        }
        let stops = Self::stops(&self.lines[self.line]);
        let previous = stops
            .iter()
            .rev()
            .copied()
            .find(|&s| s < self.at)
            .unwrap_or(0);
        self.lines[self.line].replace_range(previous..self.at, "");
        self.at = previous;
    }

    fn delete(&mut self) {
        let length = self.lines[self.line].len();
        if self.at == length {
            if self.line + 1 < self.lines.len() {
                let next = self.lines.remove(self.line + 1);
                self.lines[self.line].push_str(&next);
            }
            return;
        }
        let stops = Self::stops(&self.lines[self.line]);
        let next = stops
            .iter()
            .copied()
            .find(|&s| s > self.at)
            .unwrap_or(length);
        self.lines[self.line].replace_range(self.at..next, "");
    }

    fn left(&mut self) {
        if self.at == 0 {
            if self.line > 0 {
                self.line -= 1;
                self.at = self.lines[self.line].len();
            }
            return;
        }
        let stops = Self::stops(&self.lines[self.line]);
        self.at = stops
            .iter()
            .rev()
            .copied()
            .find(|&s| s < self.at)
            .unwrap_or(0);
    }

    fn right(&mut self) {
        let length = self.lines[self.line].len();
        if self.at == length {
            if self.line + 1 < self.lines.len() {
                self.line += 1;
                self.at = 0;
            }
            return;
        }
        let stops = Self::stops(&self.lines[self.line]);
        self.at = stops
            .iter()
            .copied()
            .find(|&s| s > self.at)
            .unwrap_or(length);
    }

    /// Move `delta` lines, keeping the column in cells as near as it goes.
    fn vertical(&mut self, delta: isize) {
        let target = self
            .line
            .saturating_add_signed(delta)
            .min(self.lines.len() - 1);
        if target == self.line {
            return;
        }
        let column = cells(&self.lines[self.line][..self.at]);
        self.line = target;
        let line = &self.lines[target];
        self.at = Self::stops(line)
            .into_iter()
            .take_while(|&stop| cells(&line[..stop]) <= column)
            .last()
            .unwrap_or(0);
    }

    fn kill_word(&mut self) {
        let line = &self.lines[self.line];
        let before = &line[..self.at];
        let trimmed = before.trim_end_matches(' ');
        let start = trimmed.rfind(' ').map_or(0, |space| space + 1);
        self.lines[self.line].replace_range(start..self.at, "");
        self.at = start;
    }

    fn gutter(&self) -> usize {
        if self.line_numbers {
            self.lines.len().to_string().len() + 3
        } else {
            2
        }
    }

    /// The rows at `width`, wrapped one cell short so the caret fits after
    /// the last character.
    fn rows(&self, width: usize) -> Vec<Row> {
        let room = width.saturating_sub(self.gutter() + 1).max(1);
        let mut rows = Vec::new();
        for (index, line) in self.lines.iter().enumerate() {
            let spans = graphemes(line);
            let mut start = 0;
            let mut cells = 0;
            let mut first = true;
            for (at, _, width) in spans {
                if cells + width > room && at > start {
                    rows.push(Row {
                        line: index,
                        start,
                        end: at,
                        first,
                    });
                    first = false;
                    start = at;
                    cells = 0;
                }
                cells += width;
            }
            rows.push(Row {
                line: index,
                start,
                end: line.len(),
                first,
            });
        }
        rows
    }

    /// The caret's row and column among `rows`.
    fn caret_at(&self, rows: &[Row]) -> (usize, usize) {
        for (index, row) in rows.iter().enumerate() {
            let next_same_line = rows
                .get(index + 1)
                .is_some_and(|next| next.line == row.line);
            let within = self.at >= row.start && (self.at < row.end || !next_same_line);
            if row.line == self.line && within {
                let line = &self.lines[row.line];
                return (index, cells(&line[row.start..self.at]));
            }
        }
        (0, 0)
    }

    /// Scroll so the caret is shown, `height` rows of text on screen.
    fn follow(&self, width: usize, height: usize) {
        let rows = self.rows(width);
        let (row, _) = self.caret_at(&rows);
        let top = self.top.get();
        if row < top {
            self.top.set(row);
        } else if row >= top + height {
            self.top.set(row + 1 - height);
        }
    }
}

/// Text for the area: `\r\n` and `\r` as `\n`, tabs kept, and other
/// terminal controls (C0, DEL, C1) dropped.
fn clean(text: &str) -> String {
    let text = text.replace("\r\n", "\n").replace('\r', "\n");
    let mut out = String::with_capacity(text.len());
    for c in text.chars() {
        match c {
            '\n' | '\t' => out.push(c),
            '\0'..='\u{1f}' | '\u{7f}'..='\u{9f}' => {}
            _ => out.push(c),
        }
    }
    out
}

impl Component for TextArea {
    type Output = String;

    fn handle(&mut self, event: &Event, context: &Context<'_>) -> Flow<String> {
        let height = self.shown_rows(context.height);
        if let Event::Paste(pasted) = event {
            self.insert(&clean(pasted));
            self.follow(context.width, height);
            return Flow::Continue;
        }
        let Some(key) = event.key() else {
            if let Event::Resize { .. } = event {
                self.follow(context.width, height);
            }
            return Flow::Continue;
        };
        if key == self.submit {
            let text = self.text();
            self.answer = Some(Some(text.clone()));
            return Flow::Done(text);
        }
        let ctrl = key.modifiers.ctrl;
        match key.code {
            KeyCode::Escape => {
                self.answer = Some(None);
                return Flow::Cancel;
            }
            KeyCode::Enter => self.insert("\n"),
            KeyCode::Tab => self.insert("    "),
            KeyCode::Backspace => self.backspace(),
            KeyCode::Delete => self.delete(),
            KeyCode::Left => self.left(),
            KeyCode::Right => self.right(),
            KeyCode::Up => self.vertical(-1),
            KeyCode::Down => self.vertical(1),
            KeyCode::PageUp => self.vertical(-(height as isize)),
            KeyCode::PageDown => self.vertical(height as isize),
            KeyCode::Home if ctrl => (self.line, self.at) = (0, 0),
            KeyCode::End if ctrl => {
                self.line = self.lines.len() - 1;
                self.at = self.lines[self.line].len();
            }
            KeyCode::Home => self.at = 0,
            KeyCode::End => self.at = self.lines[self.line].len(),
            KeyCode::Char('a') if ctrl => self.at = 0,
            KeyCode::Char('e') if ctrl => self.at = self.lines[self.line].len(),
            KeyCode::Char('u') if ctrl => {
                self.lines[self.line].replace_range(..self.at, "");
                self.at = 0;
            }
            KeyCode::Char('k') if ctrl => {
                let at = self.at;
                self.lines[self.line].truncate(at);
            }
            KeyCode::Char('w') if ctrl => self.kill_word(),
            KeyCode::Char(c) if !ctrl && !key.modifiers.alt => {
                let mut buffer = [0; 4];
                self.insert(c.encode_utf8(&mut buffer));
            }
            _ => return Flow::Ignored,
        }
        self.follow(context.width, height);
        Flow::Continue
    }

    fn keymap(&self) -> Keymap {
        Keymap::new("textarea")
            .bind("submit", [self.submit], "submit")
            .bind("cancel", keys("escape"), "cancel")
            .bind("newline", keys("enter"), "new line")
            .bind("indent", keys("tab"), "indent")
            .bind("up", keys("up"), "line up")
            .bind("down", keys("down"), "line down")
            .bind("left", keys("left"), "move left")
            .bind("right", keys("right"), "move right")
            .bind("page-up", keys("pageup"), "page up")
            .bind("page-down", keys("pagedown"), "page down")
            .bind("home", keys("home ctrl+a"), "start of the line")
            .bind("end", keys("end ctrl+e"), "end of the line")
            .bind("top", keys("ctrl+home"), "start of the text")
            .bind("bottom", keys("ctrl+end"), "end of the text")
            .bind(
                "delete-to-start",
                keys("ctrl+u"),
                "delete to the line's start",
            )
            .bind("delete-to-end", keys("ctrl+k"), "delete to the line's end")
            .bind("delete-word", keys("ctrl+w"), "delete a word")
            .bind("backspace", keys("backspace"), "delete back")
            .bind("delete", keys("delete"), "delete forward")
    }

    fn render(&self, context: &Context<'_>) -> View {
        let width = context.width;
        let theme = &self.theme;
        let mut header = question(theme, &self.prompt);
        if let Some(answer) = &self.answer {
            header.push(match answer {
                Some(answer) => {
                    let mut lines = answer.lines();
                    let first = lines.next().unwrap_or("").to_string();
                    let more = lines.count();
                    if more > 0 {
                        text(format!("{first} … (+{more} lines)"), &theme.answer)
                    } else {
                        text(first, &theme.answer)
                    }
                }
                None => text("cancelled", &theme.hint),
            });
            return View::new(vec![fit(header, width)]);
        }
        let mut lines = vec![fit(header, width)];
        let rows = self.rows(width);
        let (caret_row, caret_column) = self.caret_at(&rows);
        let height = self.shown_rows(context.height);
        let top = self.top.get().min(rows.len().saturating_sub(1));
        let gutter = self.gutter();
        let empty = self.lines.len() == 1 && self.lines[0].is_empty();
        for index in top..top + height {
            let mut line: Vec<Segment> = Vec::new();
            match rows.get(index) {
                Some(row) => {
                    let number = if self.line_numbers && row.first {
                        format!("{:>w$} │ ", row.line + 1, w = gutter - 3)
                    } else if self.line_numbers {
                        format!("{} │ ", " ".repeat(gutter - 3))
                    } else {
                        "│ ".to_string()
                    };
                    line.push(text(number, &theme.border));
                    if empty {
                        if let Some(placeholder) = &self.placeholder {
                            line.push(text(placeholder.clone(), &theme.hint));
                        }
                    } else {
                        let piece = &self.lines[row.line][row.start..row.end];
                        line.push(plain(piece.replace('\t', &" ".repeat(TAB))));
                    }
                }
                None => line.push(text(format!("{}~", " ".repeat(gutter - 2)), &theme.border)),
            }
            lines.push(fit(line, width));
        }
        let mut hint = String::from("  ");
        if let Some(limit) = self.limit {
            hint.push_str(&format!("{}/{limit} · ", self.count()));
        }
        hint.push_str(&format!(
            "enter new line · {} submit · esc cancel",
            self.submit
        ));
        lines.push(fit(vec![text(hint, &theme.hint)], width));
        let view = View::new(lines);
        if caret_row >= top && caret_row < top + height {
            view.with_cursor(
                1 + caret_row - top,
                (gutter + caret_column).min(width.saturating_sub(1)),
            )
        } else {
            view
        }
    }

    fn default_value(&self) -> Option<String> {
        Some(self.text()).filter(|text| !text.is_empty())
    }

    /// Without a terminal: every line up to the end of input is the text,
    /// cut to the character limit. No lines at all answer with the text
    /// the area started with.
    fn prompt(&mut self, io: &mut dyn LineIo) -> Result<Option<String>, NotInteractive> {
        io.write(&format!("{} (end with Ctrl+D):\n", self.prompt));
        let mut read: Vec<String> = Vec::new();
        let mut total = 0usize;
        while let Some(line) = io.read_line() {
            total += length(&line) + 1;
            read.push(clean(&line));
            if self.limit.is_some_and(|limit| total > limit) {
                break;
            }
        }
        if read.is_empty() {
            return Ok(Some(self.text()));
        }
        let text = read.join("\n");
        Ok(Some(match self.limit {
            Some(limit) => TextArea::truncate(&text, limit).to_string(),
            None => text,
        }))
    }
}

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

    #[test]
    fn wraps_long_lines_one_cell_short() {
        let area = TextArea::new("Notes").value("abcdefghij\nxy");
        // 12 columns, a 2-cell gutter, one cell kept for the caret: 9.
        let rows = area.rows(12);
        let pieces: Vec<&str> = rows
            .iter()
            .map(|row| &area.lines[row.line][row.start..row.end])
            .collect();
        assert_eq!(pieces, ["abcdefghi", "j", "xy"]);
        assert!(rows[0].first && !rows[1].first && rows[2].first);
        assert_eq!(area.caret_at(&rows), (2, 2));
    }

    #[test]
    fn cleans_pasted_text() {
        assert_eq!(clean("a\r\nb\rc\td\x1b[2Je\u{9b}"), "a\nb\nc\td[2Je");
    }
}