a3s-tui 0.1.14

TEA (The Elm Architecture) framework for terminal user interfaces
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
use crate::element::{BorderStyle as ElBorder, BoxElement, Element, FlexDirection, TextElement};
use crate::style::{
    fit_visible, split_nonempty_lines_preserving_trailing_blank, visible_len, Border, Color, Style,
};

pub struct Modal {
    title: String,
    body: String,
    options: Vec<String>,
    selected: usize,
    border: Border,
    border_color: Color,
    title_color: Color,
    selected_color: Color,
}

#[derive(Debug, Clone)]
pub enum ModalMsg {
    Next,
    Prev,
    Select(usize),
    Cancel,
}

impl Modal {
    pub fn new() -> Self {
        Self {
            title: String::new(),
            body: String::new(),
            options: Vec::new(),
            selected: 0,
            border: Border::Rounded,
            border_color: Color::BrightBlue,
            title_color: Color::BrightWhite,
            selected_color: Color::BrightCyan,
        }
    }

    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = title.into();
        self
    }

    pub fn body(mut self, body: impl Into<String>) -> Self {
        self.body = body.into();
        self
    }

    pub fn options(mut self, options: Vec<impl Into<String>>) -> Self {
        self.options = options.into_iter().map(|o| o.into()).collect();
        self.clamp_selected();
        self
    }

    pub fn selected(mut self, idx: usize) -> Self {
        self.selected = idx;
        if !self.options.is_empty() {
            self.clamp_selected();
        }
        self
    }

    pub fn border_color(mut self, color: Color) -> Self {
        self.border_color = color;
        self
    }

    pub fn update(&mut self, msg: ModalMsg) -> Option<usize> {
        match msg {
            ModalMsg::Next => {
                if !self.options.is_empty() {
                    let current = self.selected.min(self.options.len() - 1);
                    self.selected = (current + 1) % self.options.len();
                }
                None
            }
            ModalMsg::Prev => {
                if !self.options.is_empty() {
                    let current = self.selected.min(self.options.len() - 1);
                    self.selected = current.checked_sub(1).unwrap_or(self.options.len() - 1);
                }
                None
            }
            ModalMsg::Select(idx) => {
                if idx < self.options.len() {
                    self.selected = idx;
                    Some(idx)
                } else {
                    None
                }
            }
            ModalMsg::Cancel => None,
        }
    }

    pub fn confirm(&self) -> usize {
        self.normalized_selected()
    }

    pub fn view(&self, screen_width: u16, screen_height: u16) -> String {
        let screen_width = screen_width as usize;
        let screen_height = screen_height as usize;
        if screen_width == 0 || screen_height == 0 {
            return String::new();
        }

        let content_width = self.compute_width();
        let modal_width = content_width.saturating_add(4).min(screen_width);

        let mut inner_lines = Vec::new();

        if !self.title.is_empty() {
            let title_styled = Style::new().bold().fg(self.title_color).render(&self.title);
            inner_lines.push(title_styled);
            inner_lines.push(String::new());
        }

        if !self.body.is_empty() {
            for line in split_nonempty_lines_preserving_trailing_blank(&self.body) {
                inner_lines.push(line.to_string());
            }
            inner_lines.push(String::new());
        }

        let selected = self.normalized_selected();
        for (i, opt) in self.options.iter().enumerate() {
            let prefix = if i == selected { "" } else { "  " };
            let styled = if i == selected {
                Style::new()
                    .bold()
                    .fg(self.selected_color)
                    .render(&format!("{}{}", prefix, opt))
            } else {
                format!("{}{}", prefix, opt)
            };
            inner_lines.push(styled);
        }

        let box_style = Style::new()
            .border(self.border)
            .border_fg(self.border_color)
            .padding(1, 2)
            .width(modal_width as u16);

        let box_content = inner_lines.join("\n");
        let rendered_box = box_style.render(&box_content);

        let box_lines: Vec<&str> = rendered_box.lines().collect();
        let box_height = box_lines.len();

        let top_pad = screen_height.saturating_sub(box_height) / 2;
        let left_pad = screen_width.saturating_sub(modal_width) / 2;

        let mut output = Vec::new();

        for _ in 0..top_pad {
            output.push(String::new());
        }

        for line in &box_lines {
            output.push(format!("{}{}", " ".repeat(left_pad), line));
        }

        for _ in 0..screen_height.saturating_sub(top_pad + box_height) {
            output.push(String::new());
        }

        output.truncate(screen_height);
        while output.len() < screen_height {
            output.push(String::new());
        }

        output
            .into_iter()
            .map(|line| fit_visible(&line, screen_width))
            .collect::<Vec<_>>()
            .join("\n")
    }

    fn compute_width(&self) -> usize {
        let mut max_width = visible_len(&self.title);
        for line in split_nonempty_lines_preserving_trailing_blank(&self.body) {
            max_width = max_width.max(visible_len(line));
        }
        for opt in &self.options {
            max_width = max_width.max(visible_len(opt) + 2);
        }
        max_width.max(20)
    }

    fn clamp_selected(&mut self) {
        self.selected = self.selected.min(self.options.len().saturating_sub(1));
    }

    fn normalized_selected(&self) -> usize {
        self.selected.min(self.options.len().saturating_sub(1))
    }
}

impl Default for Modal {
    fn default() -> Self {
        Self::new()
    }
}

impl Modal {
    pub fn element<Msg>(&self) -> Element<Msg> {
        let mut children: Vec<Element<Msg>> = Vec::new();

        if !self.title.is_empty() {
            children.push(Element::Text(
                TextElement::new(&self.title).bold().fg(self.title_color),
            ));
            children.push(Element::Text(TextElement::new("")));
        }

        if !self.body.is_empty() {
            for line in split_nonempty_lines_preserving_trailing_blank(&self.body) {
                children.push(Element::Text(TextElement::new(line)));
            }
            children.push(Element::Text(TextElement::new("")));
        }

        let selected = self.normalized_selected();
        for (i, opt) in self.options.iter().enumerate() {
            let prefix = if i == selected { "" } else { "  " };
            let text = format!("{}{}", prefix, opt);
            if i == selected {
                children.push(Element::Text(
                    TextElement::new(text).bold().fg(self.selected_color),
                ));
            } else {
                children.push(Element::Text(TextElement::new(text)));
            }
        }

        let border = match self.border {
            Border::Rounded => ElBorder::Rounded,
            Border::Single => ElBorder::Single,
            Border::Double => ElBorder::Double,
            Border::Thick => ElBorder::Thick,
            _ => ElBorder::Rounded,
        };

        Element::Box(
            BoxElement::new()
                .direction(FlexDirection::Column)
                .border(border)
                .border_color(self.border_color)
                .padding(1)
                .children(children),
        )
    }
}

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

    #[test]
    fn modal_update_next() {
        let mut modal = Modal::new().options(vec!["A", "B", "C"]);
        modal.update(ModalMsg::Next);
        assert_eq!(modal.confirm(), 1);
        modal.update(ModalMsg::Next);
        assert_eq!(modal.confirm(), 2);
        modal.update(ModalMsg::Next);
        assert_eq!(modal.confirm(), 0); // wraps
    }

    #[test]
    fn modal_update_prev() {
        let mut modal = Modal::new().options(vec!["A", "B", "C"]);
        modal.update(ModalMsg::Prev);
        assert_eq!(modal.confirm(), 2); // wraps to end
    }

    #[test]
    fn modal_select_returns_index() {
        let mut modal = Modal::new().options(vec!["X", "Y"]);
        let result = modal.update(ModalMsg::Select(1));
        assert_eq!(result, Some(1));
        assert_eq!(modal.confirm(), 1);
    }

    #[test]
    fn modal_cancel_returns_none() {
        let mut modal = Modal::new().options(vec!["X"]);
        let result = modal.update(ModalMsg::Cancel);
        assert_eq!(result, None);
    }

    #[test]
    fn selected_index_is_clamped() {
        let modal = Modal::new().options(vec!["X", "Y"]).selected(99);

        assert_eq!(modal.confirm(), 1);
    }

    #[test]
    fn navigation_normalizes_stale_selection() {
        let mut modal = Modal::new()
            .selected(usize::MAX)
            .options(vec!["A", "B", "C"]);
        assert_eq!(modal.confirm(), 2);

        modal.update(ModalMsg::Next);
        assert_eq!(modal.confirm(), 0);

        let mut modal = Modal::new().options(vec!["A", "B", "C"]);
        modal.selected = usize::MAX;
        modal.update(ModalMsg::Prev);
        assert_eq!(modal.confirm(), 1);
    }

    #[test]
    fn rendering_normalizes_stale_selection() {
        let mut modal = Modal::new().options(vec!["A", "B"]);
        modal.selected = usize::MAX;

        let rendered = modal.view(30, 6);

        assert!(rendered.contains("▸ B"));
        assert!(!rendered.contains("▸ A"));

        let Element::Box(box_el) = modal.element::<()>() else {
            panic!("expected Box");
        };
        let Element::Text(last_option) = box_el.children.last().expect("expected last option")
        else {
            panic!("expected option text");
        };
        assert_eq!(last_option.content, "▸ B");
    }

    #[test]
    fn select_ignores_out_of_bounds_index() {
        let mut modal = Modal::new().options(vec!["X", "Y"]);

        assert_eq!(modal.update(ModalMsg::Select(99)), None);
        assert_eq!(modal.confirm(), 0);
    }

    #[test]
    fn modal_view_clamps_to_screen_size() {
        let rendered = Modal::new()
            .title("Confirm an unusually long operation title")
            .body("This body is also far longer than the available modal width.")
            .options(vec!["Accept the full operation", "Cancel"])
            .view(16, 5);

        assert_eq!(rendered.lines().count(), 5);
        for line in rendered.lines() {
            assert_eq!(visible_len(line), 16, "{line:?}");
        }
    }

    #[test]
    fn modal_view_returns_empty_for_zero_screen_dimensions() {
        let modal = Modal::new().title("Confirm").options(vec!["OK"]);

        assert_eq!(modal.view(0, 5), "");
        assert_eq!(modal.view(20, 0), "");
    }

    #[test]
    fn modal_element_has_content() {
        let modal = Modal::new()
            .title("Confirm")
            .body("Are you sure?")
            .options(vec!["Yes", "No"]);
        let el: Element<()> = modal.element();
        match el {
            Element::Box(b) => {
                // title + empty + body + empty + 2 options = 6
                assert!(b.children.len() >= 5);
            }
            _ => panic!("expected Box"),
        }
    }

    #[test]
    fn modal_element_preserves_trailing_blank_body_line() {
        let modal = Modal::new().body("Line\n").options(vec!["OK"]);
        let el: Element<()> = modal.element();

        let Element::Box(box_el) = el else {
            panic!("expected Box");
        };
        let Element::Text(body) = &box_el.children[0] else {
            panic!("expected body text");
        };
        let Element::Text(blank_body) = &box_el.children[1] else {
            panic!("expected trailing blank body row");
        };
        let Element::Text(separator) = &box_el.children[2] else {
            panic!("expected separator row");
        };

        assert_eq!(body.content, "Line");
        assert_eq!(blank_body.content, "");
        assert_eq!(separator.content, "");
    }
}