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
use crate::{cell::Cell, Constraint, Element, Line, Paint, Size};

/// Default text wrap width.
pub const DEFAULT_WRAP: usize = 80;
/// Soft tab replacement for '\t'.
pub const SOFT_TAB: &str = "  ";

/// Text area.
///
/// A block of text that can contain multiple lines.
#[derive(Debug)]
pub struct TextArea {
    body: Paint<String>,
    wrap: usize,
}

impl TextArea {
    /// Create a new text area.
    pub fn new(body: impl Into<Paint<String>>) -> Self {
        Self {
            body: body.into(),
            wrap: DEFAULT_WRAP,
        }
    }

    /// Set wrap width.
    pub fn wrap(mut self, cols: usize) -> Self {
        self.wrap = cols;
        self
    }

    /// Get the lines of text in this text area.
    pub fn lines(&self) -> impl Iterator<Item = String> {
        let mut lines: Vec<String> = Vec::new();
        let mut fenced = false;

        for line in self
            .body
            .content()
            .lines()
            // Replace tabs as their visual width cannot be calculated.
            .map(|l| l.replace('\t', SOFT_TAB))
        {
            // Fenced code block support.
            if line.starts_with("```") {
                fenced = !fenced;
            }
            // Code blocks are not wrapped, they are truncated.
            if fenced || line.starts_with('\t') || line.starts_with(' ') {
                lines.push(line.truncate(self.wrap, "…"));
                continue;
            }
            let mut current = String::new();

            for word in line.split_whitespace() {
                if current.width() + word.width() > self.wrap {
                    lines.push(current.trim_end().to_owned());
                    current = word.to_owned();
                } else {
                    current.push_str(word);
                }
                current.push(' ');
            }
            lines.push(current.trim_end().to_owned());
        }
        lines.into_iter()
    }

    /// Box the text area.
    pub fn boxed(self) -> Box<dyn Element> {
        Box::new(self)
    }
}

impl Element for TextArea {
    fn size(&self, _parent: Constraint) -> Size {
        let cols = self.lines().map(|l| l.width()).max().unwrap_or(0);
        let rows = self.lines().count();

        Size::new(cols, rows)
    }

    fn render(&self, _parent: Constraint) -> Vec<Line> {
        self.lines()
            .map(|l| Line::new(Paint::new(l).with_style(self.body.style)))
            .collect()
    }
}

/// Create a new text area.
pub fn textarea(content: impl Into<Paint<String>>) -> TextArea {
    TextArea::new(content)
}

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

    #[test]
    fn test_wrapping() {
        let t = TextArea::new(
            "Radicle enables users to run their own nodes, \
            ensuring censorship-resistant code collaboration \
            and fostering a resilient network without reliance \
            on third-parties.",
        )
        .wrap(50);
        let wrapped = t.lines().collect::<Vec<_>>();

        assert_eq!(
            wrapped,
            vec![
                "Radicle enables users to run their own nodes,".to_owned(),
                "ensuring censorship-resistant code collaboration".to_owned(),
                "and fostering a resilient network without reliance".to_owned(),
                "on third-parties.".to_owned(),
            ]
        );
    }

    #[test]
    fn test_wrapping_paragraphs() {
        let t = TextArea::new(
            "Radicle enables users to run their own nodes, \
            ensuring censorship-resistant code collaboration \
            and fostering a resilient network without reliance \
            on third-parties.\n\n\
            All social artifacts are stored in git, and signed \
            using public-key cryptography. Radicle verifies \
            the authenticity and authorship of all data \
            automatically.",
        )
        .wrap(50);
        let wrapped = t.lines().collect::<Vec<_>>();

        assert_eq!(
            wrapped,
            vec![
                "Radicle enables users to run their own nodes,".to_owned(),
                "ensuring censorship-resistant code collaboration".to_owned(),
                "and fostering a resilient network without reliance".to_owned(),
                "on third-parties.".to_owned(),
                "".to_owned(),
                "All social artifacts are stored in git, and signed".to_owned(),
                "using public-key cryptography. Radicle verifies".to_owned(),
                "the authenticity and authorship of all data".to_owned(),
                "automatically.".to_owned(),
            ]
        );
    }

    #[test]
    fn test_wrapping_code_block() {
        let t = TextArea::new(
            "\
Here's an example:

  $ git push rad://z3gqcJUoA1n9HaHKufZs5FCSGazv5/z6MksFqXN3Yhqk8pTJdUGLwATkRfQvwZXPqR2qMEhbS9wzpT
  $ rad sync

Run the above and wait for your project to sync.\
        ",
        )
        .wrap(50);
        let wrapped = t.lines().collect::<Vec<_>>();

        assert_eq!(
            wrapped,
            vec![
                "Here's an example:".to_owned(),
                "".to_owned(),
                "  $ git push rad://z3gqcJUoA1n9HaHKufZs5FCSGazv5/…".to_owned(),
                "  $ rad sync".to_owned(),
                "".to_owned(),
                "Run the above and wait for your project to sync.".to_owned()
            ]
        );
    }

    #[test]
    fn test_wrapping_fenced_block() {
        let t = TextArea::new(
            "\
Here's an example:
```
$ git push rad://z3gqcJUoA1n9HaHKufZs5FCSGazv5/z6MksFqXN3Yhqk8pTJdUGLwATkRfQvwZXPqR2qMEhbS9wzpT
$ rad sync
```
Run the above and wait for your project to sync.\
        ",
        )
        .wrap(40);
        let wrapped = t.lines().collect::<Vec<_>>();

        assert_eq!(
            wrapped,
            vec![
                "Here's an example:".to_owned(),
                "```".to_owned(),
                "$ git push rad://z3gqcJUoA1n9HaHKufZs5F…".to_owned(),
                "$ rad sync".to_owned(),
                "```".to_owned(),
                "Run the above and wait for your project".to_owned(),
                "to sync.".to_owned()
            ]
        );
    }
}