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
use crossterm::event::{Event, KeyCode, KeyModifiers};
use tty_interface::{pos, Interface, Position};

use crate::{
    dependency::DependencyState,
    device::InputDevice,
    step::{InputResult, Step},
    utility::render_segment,
    Result,
};

/// A TTY-based form with multiple steps and inputs.
///
/// # Examples
/// ```
/// # use tty_interface::{Interface, test::VirtualDevice};
/// # use tty_form::{Error, test::VirtualInputDevice};
/// # let mut device = VirtualDevice::new();
/// # let mut interface = Interface::new_relative(&mut device)?;
/// # let mut stdin = VirtualInputDevice;
/// use tty_form::{
///     Form,
///     step::{Step, CompoundStep, TextBlockStep},
///     control::{Control, TextInput},
/// };
///
/// let mut form = Form::new();
///
/// let mut name_step = CompoundStep::new();
/// TextInput::new("Enter a name:", false).add_to(&mut name_step);
/// name_step.add_to(&mut form);
///
/// TextBlockStep::new("Enter a description of this person:").add_to(&mut form);
///
/// let submission = form.execute(&mut interface, &mut stdin)?;
/// # Ok::<(), Error>(())
/// ```
pub struct Form {
    steps: Vec<Box<dyn Step>>,

    /// The currently-focused step.
    active_step: usize,

    /// The furthest step the user has reached so far.
    max_step: usize,

    /// The last render's height.
    last_height: u16,
}

impl Default for Form {
    /// Create a new, default terminal form.
    fn default() -> Self {
        Self {
            steps: Vec::new(),
            active_step: 0,
            max_step: 0,
            last_height: 0,
        }
    }
}

impl Form {
    /// Create a new, default terminal form.
    pub fn new() -> Form {
        Self::default()
    }

    /// Append and return a compound step with multiple component controls.
    pub fn add_step(&mut self, step: Box<dyn Step>) {
        self.steps.push(step);
    }

    /// Execute the provided form and return its WYSIWYG result.
    pub fn execute<D: InputDevice>(
        mut self,
        interface: &mut Interface,
        input_device: &mut D,
    ) -> Result<String> {
        let mut dependency_state = DependencyState::new();

        for (step_index, step) in self.steps.iter_mut().enumerate() {
            step.initialize(&mut dependency_state, step_index);
        }

        self.render_form(interface, &dependency_state);
        interface.apply()?;

        loop {
            interface.set_cursor(None);

            if let Event::Key(key_event) = input_device.read()? {
                if (KeyModifiers::CONTROL, KeyCode::Char('c'))
                    == (key_event.modifiers, key_event.code)
                {
                    break;
                }

                if let Some(action) =
                    self.steps[self.active_step].update(&mut dependency_state, key_event)
                {
                    match action {
                        InputResult::AdvanceForm => {
                            if self.advance() {
                                break;
                            }
                        }
                        InputResult::RetreatForm => {
                            if self.retreat() {
                                break;
                            }
                        }
                    }
                }
            }

            self.render_form(interface, &dependency_state);
            interface.apply()?;
        }

        self.render_form(interface, &dependency_state);
        interface.apply()?;

        let mut result = String::new();

        for step in self.steps {
            result.push_str(&step.result(&dependency_state));
        }

        result = result.trim().to_string();

        Ok(result)
    }

    /// Advance the form to its next step. Returns whether we've finished the form.
    fn advance(&mut self) -> bool {
        let is_last_step = self.active_step + 1 == self.steps.len();
        if !is_last_step {
            self.active_step += 1;

            if self.active_step > self.max_step {
                self.max_step = self.active_step;
            }
        }

        is_last_step
    }

    /// Retreat the form to its previous step. Returns whether we're at the first step.
    fn retreat(&mut self) -> bool {
        let is_first_step = self.active_step == 0;
        if !is_first_step {
            self.active_step -= 1;
        }

        is_first_step
    }

    /// Re-render the form's updated state.
    fn render_form(&mut self, interface: &mut Interface, dependency_state: &DependencyState) {
        for line in 0..self.last_height {
            interface.clear_line(line);
        }

        let mut drawer = None;
        let mut line = 1;
        for (step_index, step) in self.steps.iter().enumerate() {
            if step_index > self.max_step {
                break;
            }

            let step_height = step.render(
                interface,
                dependency_state,
                pos!(0, line),
                step_index == self.active_step,
            );

            line += step_height;

            if step_index == self.active_step {
                render_segment(interface, pos!(0, 0), step.help());
                drawer = step.drawer();
            }
        }

        if let Some(drawer) = drawer {
            for item in drawer {
                render_segment(interface, pos!(0, line), item);
                line += 1;
            }
        }

        self.last_height = line;
    }
}