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
use crossterm::event::{KeyCode, KeyEvent};
use tty_interface::Style;
use tty_text::{Key, Text};

use crate::CompoundStep;

/// An element of a [CompoundStep] which may be a focusable input.
pub trait Control {
    /// Whether this control is a focusable input.
    fn is_focusable(&self) -> bool;

    /// Updates the control's state from the given input event.
    fn handle_input(&mut self, key_event: KeyEvent);

    /// Get this control's descriptive help text, if available.
    fn get_help(&self) -> Option<String>;

    /// Get this control's rendered result contents.
    fn get_text(&self) -> (String, Option<u16>);

    /// Get this control's drawer contents, if available.
    fn get_drawer(&self) -> Option<Vec<String>>;

    /// Finish configuration and add this control to the specified form step.
    fn add_to_step(self, step: &mut CompoundStep);
}

/// Static, unfocusable display text. May be formatted.
///
/// # Examples
/// ```
/// use tty_form::{CompoundStep, Control, StaticText};
/// use tty_interface::Style;
///
/// let mut text = StaticText::new("Hello, world!");
/// text.set_style(Style::default().set_bold(true));
///
/// let mut step = CompoundStep::new();
/// text.add_to_step(&mut step);
/// ```
pub struct StaticText {
    text: String,
    style: Option<Style>,
}

impl Default for StaticText {
    /// Create a default static text control with no contents.
    fn default() -> Self {
        Self::new("")
    }
}

impl StaticText {
    /// Create a new static text control with the specified content.
    pub fn new(text: &str) -> Self {
        Self {
            text: text.to_string(),
            style: None,
        }
    }

    /// Set the text for this control.
    pub fn set_text(&mut self, text: &str) {
        self.text = text.to_string();
    }

    /// Set the optional style for this control.
    pub fn set_style(&mut self, style: Style) {
        self.style = Some(style);
    }
}

impl Control for StaticText {
    fn is_focusable(&self) -> bool {
        false
    }

    fn handle_input(&mut self, _key_event: KeyEvent) {}

    fn get_help(&self) -> Option<String> {
        None
    }

    fn get_text(&self) -> (String, Option<u16>) {
        (self.text.clone(), None)
    }

    fn get_drawer(&self) -> Option<Vec<String>> {
        None
    }

    fn add_to_step(self, step: &mut CompoundStep) {
        step.add_control(Box::new(self));
    }
}

/// A text field input.
///
/// # Examples
/// ```
/// use tty_form::{CompoundStep, Control, TextInput};
///
/// let mut step = CompoundStep::new();
/// TextInput::new("Enter your name:", false)
///     .add_to_step(&mut step);
/// ```
pub struct TextInput {
    prompt: String,
    text: Text,
    force_lowercase: bool,
}

impl Default for TextInput {
    /// Create a default text input with no prompt which allows mixed cases.
    fn default() -> Self {
        Self::new("", false)
    }
}

impl TextInput {
    /// Create a new text input control with the specified prompt and casing-rules.
    pub fn new(prompt: &str, force_lowercase: bool) -> Self {
        Self {
            prompt: prompt.to_string(),
            text: Text::new(false),
            force_lowercase,
        }
    }

    /// Update this input's prompt text.
    pub fn set_prompt(&mut self, prompt: &str) {
        self.prompt = prompt.to_string();
    }

    /// Specify whether this input should force its value to be lowercase.
    pub fn set_force_lowercase(&mut self, force: bool) {
        self.force_lowercase = force;
    }
}

impl Control for TextInput {
    fn is_focusable(&self) -> bool {
        true
    }

    fn handle_input(&mut self, key_event: KeyEvent) {
        match key_event.code {
            KeyCode::Char(mut ch) => {
                if self.force_lowercase {
                    ch = ch.to_lowercase().next().unwrap();
                }

                self.text.handle_input(Key::Char(ch));
            }
            KeyCode::Backspace => self.text.handle_input(Key::Backspace),
            KeyCode::Left => self.text.handle_input(Key::Left),
            KeyCode::Right => self.text.handle_input(Key::Right),
            _ => {}
        }
    }

    fn get_help(&self) -> Option<String> {
        Some(self.prompt.clone())
    }

    fn get_text(&self) -> (String, Option<u16>) {
        (self.text.value(), Some(self.text.cursor().0 as u16))
    }

    fn get_drawer(&self) -> Option<Vec<String>> {
        None
    }

    fn add_to_step(self, step: &mut CompoundStep) {
        step.add_control(Box::new(self))
    }
}

/// An option selection field.
///
/// # Examples
/// ```
/// use tty_form::{CompoundStep, Control, SelectInput};
/// use tty_interface::Style;
///
/// let mut step = CompoundStep::new();
/// SelectInput::new("Select favorite food:", vec![
///     ("Pizza", "A supreme pizza."),
///     ("Burgers", "A hamburger with cheese."),
///     ("Fries", "Simple potato french-fries."),
/// ]).add_to_step(&mut step);
/// ```
pub struct SelectInput {
    prompt: String,
    options: Vec<SelectInputOption>,
    selected_option: usize,
}

impl Default for SelectInput {
    /// Create a new option-selection input with no options.
    fn default() -> Self {
        Self::new("", Vec::new())
    }
}

impl SelectInput {
    /// Create a new option-selection input with the specified prompt and options.
    pub fn new(prompt: &str, options: Vec<(&str, &str)>) -> Self {
        Self {
            prompt: prompt.to_string(),
            options: options
                .iter()
                .map(|(value, description)| SelectInputOption::new(value, description))
                .collect(),
            selected_option: 0,
        }
    }

    /// Update this input's prompt text.
    pub fn set_prompt(&mut self, prompt: &str) {
        self.prompt = prompt.to_string();
    }

    /// Add an option to this input's list.
    pub fn add_option(&mut self, option: SelectInputOption) {
        self.options.push(option);
    }

    /// Set this input's options.
    pub fn set_options(&mut self, options: Vec<SelectInputOption>) {
        self.options = options;
    }
}

impl Control for SelectInput {
    fn is_focusable(&self) -> bool {
        true
    }

    fn handle_input(&mut self, key_event: KeyEvent) {
        match key_event.code {
            KeyCode::Up => {
                if self.selected_option == 0 {
                    self.selected_option = self.options.len() - 1;
                } else {
                    self.selected_option -= 1;
                }
            }
            KeyCode::Down => {
                if self.selected_option + 1 == self.options.len() {
                    self.selected_option = 0;
                } else {
                    self.selected_option += 1;
                }
            }
            _ => {}
        }
    }

    fn get_help(&self) -> Option<String> {
        Some(self.prompt.clone())
    }

    fn get_text(&self) -> (String, Option<u16>) {
        (self.options[self.selected_option].value.clone(), Some(0))
    }

    fn get_drawer(&self) -> Option<Vec<String>> {
        let mut items = Vec::new();

        for option in &self.options {
            items.push(format!("{} - {}", option.value, option.description));
        }

        Some(items)
    }

    fn add_to_step(self, step: &mut CompoundStep) {
        step.add_control(Box::new(self))
    }
}

/// A option for an option selection input.
pub struct SelectInputOption {
    value: String,
    description: String,
}

impl SelectInputOption {
    /// Create a new option with the specified value and description.
    pub fn new(value: &str, description: &str) -> Self {
        Self {
            value: value.to_string(),
            description: description.to_string(),
        }
    }

    /// This option's value.
    pub fn value(&self) -> &str {
        &self.value
    }

    /// This option's descriptive text.
    pub fn description(&self) -> &str {
        &self.description
    }
}