aether-tui 0.1.7

A lightweight terminal UI rendering library for building rich CLI applications
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
use crate::components::{Component, Event, ViewContext};
use crate::focus::FocusRing;
use crate::line::Line;
use crate::rendering::frame::Frame;
use crate::style::Style;

use super::checkbox::Checkbox;
use super::multi_select::MultiSelect;
use super::number_field::NumberField;
use super::radio_select::RadioSelect;
use super::text_field::TextField;
use crossterm::event::KeyCode;

/// Messages emitted by [`Form`] input handling.
pub enum FormMessage {
    Close,
    Submit,
}

#[doc = include_str!("../docs/form.md")]
pub struct Form {
    pub message: String,
    pub fields: Vec<FormField>,
    focus: FocusRing,
}

/// A single field within a [`Form`].
pub struct FormField {
    pub name: String,
    pub label: String,
    pub description: Option<String>,
    pub required: bool,
    pub kind: FormFieldKind,
}

/// The widget type backing a [`FormField`].
pub enum FormFieldKind {
    Text(TextField),
    Number(NumberField),
    Boolean(Checkbox),
    SingleSelect(RadioSelect),
    MultiSelect(MultiSelect),
}

impl Form {
    pub fn new(message: String, fields: Vec<FormField>) -> Self {
        let len = fields.len();
        Self {
            message,
            fields,
            focus: FocusRing::new(len + 1), // +1 for virtual Submit tab
        }
    }

    pub fn to_json(&self) -> serde_json::Value {
        let mut map = serde_json::Map::new();
        for field in &self.fields {
            map.insert(field.name.clone(), field.kind.to_json());
        }
        serde_json::Value::Object(map)
    }

    fn is_on_submit_tab(&self) -> bool {
        self.focus.focused() == self.fields.len()
    }

    fn active_field_uses_horizontal_arrows(&self) -> bool {
        self.fields
            .get(self.focus.focused())
            .is_some_and(|f| matches!(f.kind, FormFieldKind::Text(_) | FormFieldKind::Number(_)))
    }

    fn render_tab_bar(&self, context: &ViewContext) -> Line {
        let mut line = Line::default();
        let muted = context.theme.text_secondary();
        let primary = context.theme.primary();
        let success = context.theme.success();

        for (i, field) in self.fields.iter().enumerate() {
            if i > 0 {
                line.push_styled(" · ", muted);
            }

            let is_active = self.focus.is_focused(i);
            let indicator = if field.kind.is_answered() { "✓ " } else { "□ " };

            let style = if is_active { Style::fg(primary).bold() } else { Style::fg(muted) };
            line.push_with_style(format!("{indicator}{}", field.label), style);
        }

        // Submit tab
        if !self.fields.is_empty() {
            line.push_styled(" · ", muted);
        }
        let submit_style = if self.is_on_submit_tab() { Style::fg(success).bold() } else { Style::fg(muted) };
        line.push_with_style("Submit", submit_style);

        line
    }

    fn render_active_field(&self, context: &ViewContext) -> Vec<Line> {
        if self.is_on_submit_tab() {
            return self.render_submit_summary(context);
        }

        let Some(field) = self.fields.get(self.focus.focused()) else {
            return vec![];
        };

        let mut lines = Vec::new();
        let required_marker = if field.required { "*" } else { "" };
        let label_line = Line::with_style(
            format!("{}{required_marker}: ", field.label),
            Style::fg(context.theme.text_primary()).bold(),
        );

        let field_lines = field.kind.render_field(context, true);
        let inline = field.kind.is_inline();
        if inline {
            let mut combined = label_line;
            if let Some((first, rest)) = field_lines.split_first() {
                combined.append_line(first);
                lines.push(combined);
                lines.extend_from_slice(rest);
            } else {
                lines.push(combined);
            }
        } else {
            // Multi-line widgets (radio, multi-select): label on its own line.
            lines.push(label_line);
            lines.extend(field_lines);
        }

        if let Some(desc) = &field.description {
            lines.push(Line::styled(desc, context.theme.muted()));
        }

        lines
    }

    fn render_submit_summary(&self, context: &ViewContext) -> Vec<Line> {
        let mut lines = vec![Line::with_style("Review & Submit", Style::fg(context.theme.text_primary()).bold())];
        lines.push(Line::default());

        for field in &self.fields {
            let mut line = Line::with_style(format!("{}: ", field.label), Style::fg(context.theme.text_secondary()));
            let value_lines = field.kind.render_field(context, false);
            if let Some(first) = value_lines.first() {
                line.append_line(first);
            }
            lines.push(line);
        }

        lines
    }

    fn render_footer(&self, context: &ViewContext) -> Line {
        let muted = context.theme.muted();

        if self.is_on_submit_tab() {
            return Line::styled("Enter to submit · Esc to cancel", muted);
        }

        let Some(field) = self.fields.get(self.focus.focused()) else {
            return Line::default();
        };

        let hints = match &field.kind {
            FormFieldKind::Text(_) | FormFieldKind::Number(_) => "Type your answer · Tab to navigate · Esc to cancel",
            FormFieldKind::Boolean(_) => "Space to toggle · Tab to navigate · Esc to cancel",
            FormFieldKind::SingleSelect(_) => "↑↓ to select · Tab to navigate · Enter to confirm · Esc to cancel",
            FormFieldKind::MultiSelect(_) => "Space to toggle · ↑↓ to move · Tab to navigate · Esc to cancel",
        };

        Line::styled(hints, muted)
    }
}

impl FormFieldKind {
    /// Returns `true` for widgets that render on a single line (text, number, checkbox)
    /// and `false` for multi-line widgets (radio select, multi-select).
    pub fn is_inline(&self) -> bool {
        matches!(self, Self::Text(_) | Self::Number(_) | Self::Boolean(_))
    }

    pub fn is_answered(&self) -> bool {
        match self {
            Self::Text(w) => !w.value.is_empty(),
            Self::Number(w) => !w.value.is_empty(),
            Self::Boolean(_) | Self::SingleSelect(_) => true,
            Self::MultiSelect(w) => w.selected.iter().any(|&s| s),
        }
    }

    fn to_json(&self) -> serde_json::Value {
        match self {
            Self::Text(w) => w.to_json(),
            Self::Number(w) => w.to_json(),
            Self::Boolean(w) => w.to_json(),
            Self::SingleSelect(w) => w.to_json(),
            Self::MultiSelect(w) => w.to_json(),
        }
    }

    fn render_field(&self, context: &ViewContext, focused: bool) -> Vec<Line> {
        match self {
            Self::Text(w) => w.render_field(context, focused),
            Self::Number(w) => w.render_field(context, focused),
            Self::Boolean(w) => w.render_field(context, focused),
            Self::SingleSelect(w) => w.render_field(context, focused),
            Self::MultiSelect(w) => w.render_field(context, focused),
        }
    }

    async fn handle_event(&mut self, event: &Event) -> Option<Vec<()>> {
        match self {
            Self::Text(w) => w.on_event(event).await,
            Self::Number(w) => w.on_event(event).await,
            Self::Boolean(w) => w.on_event(event).await,
            Self::SingleSelect(w) => w.on_event(event).await,
            Self::MultiSelect(w) => w.on_event(event).await,
        }
    }
}

impl Component for Form {
    type Message = FormMessage;

    async fn on_event(&mut self, event: &Event) -> Option<Vec<Self::Message>> {
        let Event::Key(key) = event else {
            return None;
        };
        match key.code {
            KeyCode::Esc => return Some(vec![FormMessage::Close]),
            KeyCode::Enter => {
                if self.is_on_submit_tab() {
                    return Some(vec![FormMessage::Submit]);
                }
                self.focus.focus_next();
                return Some(vec![]);
            }
            KeyCode::Tab => {
                self.focus.focus_next();
                return Some(vec![]);
            }
            KeyCode::BackTab => {
                self.focus.focus_prev();
                return Some(vec![]);
            }
            KeyCode::Left if !self.active_field_uses_horizontal_arrows() => {
                self.focus.focus_prev();
                return Some(vec![]);
            }
            KeyCode::Right if !self.active_field_uses_horizontal_arrows() => {
                self.focus.focus_next();
                return Some(vec![]);
            }
            _ => {}
        }

        if let Some(field) = self.fields.get_mut(self.focus.focused()) {
            field.kind.handle_event(event).await;
        }
        Some(vec![])
    }

    fn render(&mut self, context: &ViewContext) -> Frame {
        let mut lines = vec![Line::with_style(&self.message, Style::fg(context.theme.text_primary()).bold())];
        lines.push(Line::default());
        lines.push(self.render_tab_bar(context));
        lines.push(Line::default());
        lines.extend(self.render_active_field(context));
        lines.push(Line::default());
        lines.push(self.render_footer(context));
        Frame::new(lines)
    }
}

#[cfg(test)]
mod tests {
    use super::super::select_option::SelectOption;
    use super::*;
    use crate::rendering::line::Line;
    use crossterm::event::{KeyEvent, KeyModifiers};

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    fn sample_fields() -> Vec<FormField> {
        vec![
            FormField {
                name: "lang".to_string(),
                label: "Language".to_string(),
                description: Some("Pick a language".to_string()),
                required: true,
                kind: FormFieldKind::SingleSelect(RadioSelect::new(
                    vec![
                        SelectOption { value: "rust".into(), title: "Rust".into(), description: None },
                        SelectOption { value: "ts".into(), title: "TypeScript".into(), description: None },
                    ],
                    0,
                )),
            },
            FormField {
                name: "name".to_string(),
                label: "Name".to_string(),
                description: None,
                required: false,
                kind: FormFieldKind::Text(TextField::new(String::new())),
            },
            FormField {
                name: "features".to_string(),
                label: "Features".to_string(),
                description: None,
                required: false,
                kind: FormFieldKind::MultiSelect(MultiSelect::new(
                    vec![
                        SelectOption { value: "a".into(), title: "Alpha".into(), description: None },
                        SelectOption { value: "b".into(), title: "Beta".into(), description: None },
                    ],
                    vec![false, false],
                )),
            },
        ]
    }

    #[test]
    fn render_does_not_panic_when_title_wider_than_terminal() {
        let mut form = Form::new(
            "This is a very long message that exceeds the terminal width".to_string(),
            vec![FormField {
                name: "name".to_string(),
                label: "Name".to_string(),
                description: None,
                required: false,
                kind: FormFieldKind::Text(TextField::new(String::new())),
            }],
        );
        let context = ViewContext::new((10, 10));

        // Should not panic
        let frame = form.render(&context);
        assert!(!frame.lines().is_empty());
    }

    #[test]
    fn tab_bar_shows_all_field_labels() {
        let form = Form::new("Survey".to_string(), sample_fields());
        let context = ViewContext::new((80, 24));
        let tab_bar = form.render_tab_bar(&context);
        let text = tab_bar.plain_text();
        assert!(text.contains("Language"), "tab bar missing 'Language'");
        assert!(text.contains("Name"), "tab bar missing 'Name'");
        assert!(text.contains("Features"), "tab bar missing 'Features'");
        assert!(text.contains("Submit"), "tab bar missing 'Submit'");
    }

    #[test]
    fn renders_only_active_field() {
        let mut form = Form::new("Survey".to_string(), sample_fields());
        let context = ViewContext::new((80, 24));

        // Focus is on field 0 (Language / RadioSelect)
        let frame = form.render(&context);
        let text: String = frame.lines().iter().map(Line::plain_text).collect::<Vec<_>>().join("\n");
        // The active field's options should be visible
        assert!(text.contains("Rust"), "active field options not visible");
        assert!(text.contains("TypeScript"), "active field options not visible");
        // The non-active fields' expanded content should NOT be visible
        // (MultiSelect options Alpha/Beta should not appear as expanded options)
        // But the tab bar mentions "Features", so just check that the expanded
        // checkbox options aren't rendered
        assert!(!text.contains("Alpha"), "inactive field content should not appear");
    }

    #[tokio::test]
    async fn tab_advances_to_next_pane() {
        let mut form = Form::new("Survey".to_string(), sample_fields());
        assert_eq!(form.focus.focused(), 0);
        form.on_event(&Event::Key(key(KeyCode::Tab))).await;
        assert_eq!(form.focus.focused(), 1);
        form.on_event(&Event::Key(key(KeyCode::Tab))).await;
        assert_eq!(form.focus.focused(), 2);
        form.on_event(&Event::Key(key(KeyCode::Tab))).await;
        assert_eq!(form.focus.focused(), 3); // Submit tab
    }

    #[tokio::test]
    async fn enter_on_submit_tab_emits_submit() {
        let mut form = Form::new("Survey".to_string(), sample_fields());
        // Navigate to submit tab (index 3)
        form.focus.focus(3);
        let msgs = form.on_event(&Event::Key(key(KeyCode::Enter))).await.unwrap();
        assert!(msgs.iter().any(|m| matches!(m, FormMessage::Submit)));
    }

    #[tokio::test]
    async fn enter_on_field_advances() {
        let mut form = Form::new("Survey".to_string(), sample_fields());
        assert_eq!(form.focus.focused(), 0);
        form.on_event(&Event::Key(key(KeyCode::Enter))).await;
        assert_eq!(form.focus.focused(), 1);
    }

    #[tokio::test]
    async fn left_right_navigate_tabs_for_select_fields() {
        let mut form = Form::new("Survey".to_string(), sample_fields());
        // Field 0 is a RadioSelect — Right should navigate to next tab
        assert_eq!(form.focus.focused(), 0);
        form.on_event(&Event::Key(key(KeyCode::Right))).await;
        assert_eq!(form.focus.focused(), 1);

        // Field 2 is a MultiSelect — Left should navigate to previous tab
        form.focus.focus(2);
        form.on_event(&Event::Key(key(KeyCode::Left))).await;
        assert_eq!(form.focus.focused(), 1);
    }

    #[tokio::test]
    async fn left_right_delegate_to_text_field() {
        let mut form = Form::new("Survey".to_string(), sample_fields());
        // Navigate to field 1 (Text field), type something, then use Left
        form.focus.focus(1);
        form.on_event(&Event::Key(key(KeyCode::Char('h')))).await;
        form.on_event(&Event::Key(key(KeyCode::Char('i')))).await;
        assert_eq!(form.focus.focused(), 1);

        // Left should move cursor within text field, not change tab
        form.on_event(&Event::Key(key(KeyCode::Left))).await;
        assert_eq!(form.focus.focused(), 1); // still on same tab

        // Verify the cursor moved in the text field
        if let FormFieldKind::Text(ref tf) = form.fields[1].kind {
            assert_eq!(tf.cursor_pos(), 1); // moved left from 2 to 1
        } else {
            panic!("expected Text field");
        }
    }

    #[test]
    fn is_answered_text_field() {
        assert!(!FormFieldKind::Text(TextField::new(String::new())).is_answered());
        assert!(FormFieldKind::Text(TextField::new("hello".to_string())).is_answered());
    }

    #[test]
    fn is_answered_multi_select() {
        let none_selected = FormFieldKind::MultiSelect(MultiSelect::new(
            vec![SelectOption { value: "a".into(), title: "A".into(), description: None }],
            vec![false],
        ));
        assert!(!none_selected.is_answered());

        let some_selected = FormFieldKind::MultiSelect(MultiSelect::new(
            vec![SelectOption { value: "a".into(), title: "A".into(), description: None }],
            vec![true],
        ));
        assert!(some_selected.is_answered());
    }

    #[tokio::test]
    async fn esc_emits_close() {
        let mut form = Form::new("Survey".to_string(), sample_fields());
        let msgs = form.on_event(&Event::Key(key(KeyCode::Esc))).await.unwrap();
        assert!(msgs.iter().any(|m| matches!(m, FormMessage::Close)));
    }

    #[tokio::test]
    async fn backtab_moves_backward() {
        let mut form = Form::new("Survey".to_string(), sample_fields());
        form.focus.focus(2);
        form.on_event(&Event::Key(KeyEvent::new(KeyCode::BackTab, KeyModifiers::SHIFT))).await;
        assert_eq!(form.focus.focused(), 1);
    }

    #[test]
    fn submit_tab_renders_summary() {
        let mut form = Form::new("Survey".to_string(), sample_fields());
        form.focus.focus(3); // Submit tab
        let context = ViewContext::new((80, 24));
        let frame = form.render(&context);
        let text: String = frame.lines().iter().map(Line::plain_text).collect::<Vec<_>>().join("\n");
        assert!(text.contains("Review & Submit"));
        assert!(text.contains("Language:"));
        assert!(text.contains("Name:"));
    }
}