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
use std::{
    char,
    io::{self, Write},
};

use console::{Key, Term};
use termcolor::{Buffer, WriteColor};

use crate::Theme;

/// Single line text input
///
/// # Example
/// ```rust
/// use demand::Input;
///
/// let input = Input::new("What's your name?")
///   .description("We'll use this to personalize your experience.")
///   .placeholder("Enter your name");
/// let name = input.run().expect("error running input");
pub struct Input {
    /// The title of the input
    pub title: String,
    /// A description to display after the title
    pub description: String,
    /// A prompt to display after the description
    pub prompt: String,
    /// A placeholder to display in the input
    pub placeholder: String,
    /// Show the input inline
    pub inline: bool,
    /// Whether to mask the input
    pub password: bool,
    /// Input entered by the user
    pub input: String,
    /// Colors/style of the input
    pub theme: Theme,

    height: usize,
    term: Term,
}

impl Input {
    /// Creates a new input with the given title.
    pub fn new<S: Into<String>>(title: S) -> Self {
        Self {
            title: title.into(),
            description: String::new(),
            placeholder: String::new(),
            prompt: String::new(),
            input: String::new(),
            inline: false,
            password: false,
            theme: Theme::default(),
            height: 0,
            term: Term::stderr(),
        }
    }

    /// Sets the description of the input.
    /// If the input is inline, it is displayed to the right of the title. Otherwise, it is displayed below the title.
    pub fn description(mut self, description: &str) -> Self {
        self.description = description.to_string();
        self
    }

    /// Sets the inline flag of the input.
    /// If true, the input is displayed inline with the title
    pub fn inline(mut self, inline: bool) -> Self {
        self.inline = inline;
        self
    }

    /// Sets the password flag of the input.
    /// If true, the input is masked with asterisks
    pub fn password(mut self, password: bool) -> Self {
        self.password = password;
        self
    }

    /// Sets the placeholder of the input.
    /// The placeholder is displayed in the input before the user enters any text
    pub fn placeholder(mut self, placeholder: &str) -> Self {
        self.placeholder = placeholder.to_string();
        self
    }

    /// Sets the prompt of the input.
    /// The prompt is displayed after the title and description. If empty, the default prompt `>` is displayed.
    pub fn prompt(mut self, prompt: &str) -> Self {
        self.prompt = prompt.to_string();
        self
    }

    /// Sets the theme of the input
    pub fn theme(mut self, theme: Theme) -> Self {
        self.theme = theme;
        self
    }

    /// Displays the input to the user and returns the response
    pub fn run(mut self) -> io::Result<String> {
        let output = self.render()?;
        self.height = output.lines().count() - 1;
        self.term.write_all(output.as_bytes())?;
        self.term.flush()?;
        self.term.show_cursor()?;
        self.render_placeholder()?;
        loop {
            match self.term.read_key()? {
                Key::Char(c) => self.handle_key(c)?,
                Key::Backspace => self.handle_backspace()?,
                Key::Enter => {
                    return self.handle_submit();
                }
                _ => {}
            }

            let chars_count = self.input.chars().count();
            if chars_count > 0 {
                self.clear_placeholder()?;
                self.term.clear_chars(chars_count - 1)?;
            } else {
                self.render_placeholder()?;
            }

            let input = self.render_input()?;
            self.term.write_all(input.as_bytes())?;
            self.term.flush()?;
        }
    }

    fn handle_key(&mut self, c: char) -> io::Result<()> {
        self.input.push(c);
        Ok(())
    }

    fn handle_backspace(&mut self) -> io::Result<()> {
        let chars_count = self.input.chars().count();
        if chars_count > 1 {
            self.term.move_cursor_left(1)?;
        }
        if chars_count > 0 {
            self.input.pop();
            self.term.clear_chars(1)?;
        }
        Ok(())
    }

    fn handle_submit(mut self) -> io::Result<String> {
        self.clear()?;
        let output = self.render_success()?;
        self.term.write_all(output.as_bytes())?;
        Ok(self.input)
    }

    fn render(&self) -> io::Result<String> {
        let mut out = Buffer::ansi();

        out.set_color(&self.theme.title)?;
        match self.inline {
            true => write!(out, "{}", self.title)?,
            false => writeln!(out, "{}", self.title)?,
        }

        out.set_color(&self.theme.description)?;
        if !self.description.is_empty() {
            match self.inline {
                true => write!(out, "{}", self.description)?,
                false => writeln!(out, "{}", self.description)?,
            }
        }

        out.set_color(&self.theme.input_prompt)?;
        if !self.prompt.is_empty() {
            match self.inline {
                true => write!(out, "> ")?,
                false => write!(out, "{}", self.prompt)?,
            }
        }

        out.reset()?;
        Ok(std::str::from_utf8(out.as_slice()).unwrap().to_string())
    }

    fn render_placeholder(&mut self) -> io::Result<()> {
        if !self.placeholder.is_empty() {
            let mut out = Buffer::ansi();
            out.set_color(&self.theme.input_placeholder)?;
            out.write_all(self.placeholder.as_bytes())?;
            self.term.write_all(out.as_slice())?;
            self.term
                .move_cursor_left(self.placeholder.chars().count())?;
            self.term.flush()?;
            out.reset()?;
        }
        Ok(())
    }

    fn clear_placeholder(&mut self) -> io::Result<()> {
        if !self.placeholder.is_empty() {
            let placeholder_count = self.placeholder.chars().count();
            self.term.move_cursor_right(placeholder_count)?;
            self.term.clear_chars(placeholder_count)?;
        }
        Ok(())
    }

    fn render_input(&mut self) -> io::Result<String> {
        let input = match self.password {
            true => self.input.chars().map(|_| '*').collect::<String>(),
            false => self.input.to_string(),
        };
        Ok(input)
    }

    fn render_success(&mut self) -> io::Result<String> {
        let mut out = Buffer::ansi();
        out.set_color(&self.theme.title)?;
        write!(out, "{}", self.title)?;
        out.set_color(&self.theme.selected_option)?;
        writeln!(out, " {}", &self.render_input()?.to_string())?;
        out.reset()?;
        Ok(std::str::from_utf8(out.as_slice()).unwrap().to_string())
    }

    fn clear(&mut self) -> io::Result<()> {
        self.term.clear_to_end_of_screen()?;
        self.term.clear_last_lines(self.height)?;
        self.height = 0;
        Ok(())
    }
}