crates/tui-core/src/textarea.rs 6.4 KiB raw
1
//! Wrapped multi-line text widget.
2
//!
3
//! `TextArea` stores plain text plus body style and exposes wrapped lines for a
4
//! target width. It is useful both as a widget and as a line producer for
5
//! scrollable previews.
6
7
use super::{Buffer, Constraint, Line, Paint, Size, Widget, cell::Text};
8
9
/// Default text wrap width.
10
pub const DEFAULT_WRAP: usize = 80;
11
/// Soft tab replacement for '\t'.
12
pub const SOFT_TAB: &str = "  ";
13
14
/// Text area.
15
///
16
/// A block of text that can contain multiple lines.
17
#[derive(Debug)]
18
pub struct TextArea {
19
    body: Paint<String>,
20
    wrap: usize,
21
}
22
23
impl TextArea {
24
    /// Creates a new text area.
25
    pub fn new(body: impl Into<Paint<String>>) -> Self {
26
        Self {
27
            body: body.into(),
28
            wrap: DEFAULT_WRAP,
29
        }
30
    }
31
32
    /// Sets the wrap width.
33
    pub fn wrap(mut self, cols: usize) -> Self {
34
        self.wrap = cols;
35
        self
36
    }
37
38
    /// Returns the lines of text in this text area.
39
    pub fn lines(&self) -> impl Iterator<Item = String> + use<> {
40
        let mut lines: Vec<String> = Vec::new();
41
        let mut fenced = false;
42
43
        for line in self
44
            .body
45
            .content()
46
            .lines()
47
            // Replace tabs as their visual width cannot be calculated.
48
            .map(|l| l.replace('\t', SOFT_TAB))
49
        {
50
            // Fenced code block support.
51
            if line.starts_with("```") {
52
                fenced = !fenced;
53
            }
54
            // Code blocks are not wrapped, they are truncated.
55
            if fenced || line.starts_with('\t') || line.starts_with(' ') {
56
                lines.push(line.truncate(self.wrap, "…"));
57
                continue;
58
            }
59
            let mut current = String::new();
60
61
            for word in line.split_whitespace() {
62
                if current.width() + word.width() > self.wrap {
63
                    lines.push(current.trim_end().to_owned());
64
                    word.clone_into(&mut current);
65
                } else {
66
                    current.push_str(word);
67
                }
68
                current.push(' ');
69
            }
70
            lines.push(current.trim_end().to_owned());
71
        }
72
        lines.into_iter()
73
    }
74
75
    /// Boxes the text area.
76
    pub fn boxed(self) -> Box<dyn Widget> {
77
        Box::new(self)
78
    }
79
}
80
81
impl Widget for TextArea {
82
    fn size(&self, _parent: Constraint) -> Size {
83
        let cols = self.lines().map(|l| l.width()).max().unwrap_or(0);
84
        let rows = self.lines().count();
85
86
        Size::new(cols, rows)
87
    }
88
89
    fn render(&mut self, area: crate::Rect, buf: &mut Buffer) {
90
        Line::renders(
91
            TextArea::lines(self).map(|l| Line::new(Paint::new(l).with_style(self.body.style))),
92
            area,
93
            buf,
94
        );
95
    }
96
}
97
98
/// Creates a new text area.
99
pub fn textarea(content: impl Into<Paint<String>>) -> TextArea {
100
    TextArea::new(content)
101
}
102
103
#[cfg(test)]
104
mod tests {
105
    use super::*;
106
107
    #[test]
108
    fn test_wrapping() {
109
        let t = TextArea::new(
110
            "Radicle enables users to run their own nodes, \
111
            ensuring censorship-resistant code collaboration \
112
            and fostering a resilient network without reliance \
113
            on third-parties.",
114
        )
115
        .wrap(50);
116
        let wrapped = t.lines().collect::<Vec<_>>();
117
118
        assert_eq!(
119
            wrapped,
120
            vec![
121
                "Radicle enables users to run their own nodes,".to_owned(),
122
                "ensuring censorship-resistant code collaboration".to_owned(),
123
                "and fostering a resilient network without reliance".to_owned(),
124
                "on third-parties.".to_owned(),
125
            ]
126
        );
127
    }
128
129
    #[test]
130
    fn test_wrapping_paragraphs() {
131
        let t = TextArea::new(
132
            "Radicle enables users to run their own nodes, \
133
            ensuring censorship-resistant code collaboration \
134
            and fostering a resilient network without reliance \
135
            on third-parties.\n\n\
136
            All social artifacts are stored in git, and signed \
137
            using public-key cryptography. Radicle verifies \
138
            the authenticity and authorship of all data \
139
            automatically.",
140
        )
141
        .wrap(50);
142
        let wrapped = t.lines().collect::<Vec<_>>();
143
144
        assert_eq!(
145
            wrapped,
146
            vec![
147
                "Radicle enables users to run their own nodes,".to_owned(),
148
                "ensuring censorship-resistant code collaboration".to_owned(),
149
                "and fostering a resilient network without reliance".to_owned(),
150
                "on third-parties.".to_owned(),
151
                String::new(),
152
                "All social artifacts are stored in git, and signed".to_owned(),
153
                "using public-key cryptography. Radicle verifies".to_owned(),
154
                "the authenticity and authorship of all data".to_owned(),
155
                "automatically.".to_owned(),
156
            ]
157
        );
158
    }
159
160
    #[test]
161
    fn test_wrapping_code_block() {
162
        let t = TextArea::new(
163
            "\
164
Here's an example:
165
166
  $ git push rad://z3gqcJUoA1n9HaHKufZs5FCSGazv5/z6MksFqXN3Yhqk8pTJdUGLwATkRfQvwZXPqR2qMEhbS9wzpT
167
  $ rad sync
168
169
Run the above and wait for your project to sync.\
170
        ",
171
        )
172
        .wrap(50);
173
        let wrapped = t.lines().collect::<Vec<_>>();
174
175
        assert_eq!(
176
            wrapped,
177
            vec![
178
                "Here's an example:".to_owned(),
179
                String::new(),
180
                "  $ git push rad://z3gqcJUoA1n9HaHKufZs5FCSGazv5/…".to_owned(),
181
                "  $ rad sync".to_owned(),
182
                String::new(),
183
                "Run the above and wait for your project to sync.".to_owned()
184
            ]
185
        );
186
    }
187
188
    #[test]
189
    fn test_wrapping_fenced_block() {
190
        let t = TextArea::new(
191
            "\
192
Here's an example:
193
```
194
$ git push rad://z3gqcJUoA1n9HaHKufZs5FCSGazv5/z6MksFqXN3Yhqk8pTJdUGLwATkRfQvwZXPqR2qMEhbS9wzpT
195
$ rad sync
196
```
197
Run the above and wait for your project to sync.\
198
        ",
199
        )
200
        .wrap(40);
201
        let wrapped = t.lines().collect::<Vec<_>>();
202
203
        assert_eq!(
204
            wrapped,
205
            vec![
206
                "Here's an example:".to_owned(),
207
                "```".to_owned(),
208
                "$ git push rad://z3gqcJUoA1n9HaHKufZs5F…".to_owned(),
209
                "$ rad sync".to_owned(),
210
                "```".to_owned(),
211
                "Run the above and wait for your project".to_owned(),
212
                "to sync.".to_owned()
213
            ]
214
        );
215
    }
216
}