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
use std::iter::once;

use crate::Status;
use itertools::chain;
use ratatui::{
    crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers},
    prelude::*,
    widgets::StatefulWidget,
};

/// A prompt that can be drawn to a terminal.
pub trait Prompt: StatefulWidget {
    /// Draws the prompt widget.
    ///
    /// This is in addition to the [`StatefulWidget`] trait implementation as we need the [`Frame`]
    /// to set the cursor position.
    ///
    /// [`StatefulWidget`]: ratatui::widgets::StatefulWidget
    /// [`Frame`]: ratatui::Frame
    fn draw(self, frame: &mut Frame, area: Rect, state: &mut Self::State);
}

/// The focus state of a prompt.
#[derive(Debug, Clone, Default, Copy, PartialEq, Eq, Hash)]
pub enum FocusState {
    #[default]
    Unfocused,
    Focused,
}

/// The state of a prompt.
///
/// Keybindings:
/// - Enter: Complete
/// - Esc | Ctrl+C: Abort
/// - Left | Ctrl+B: Move cursor left
/// - Right | Ctrl+F: Move cursor right
/// - Home | Ctrl+A: Move cursor to start of line
/// - End | Ctrl+E: Move cursor to end of line
/// - Backspace | Ctrl+H: Delete character before cursor
/// - Delete | Ctrl+D: Delete character after cursor
/// - Ctrl+K: Delete from cursor to end of line
/// - Ctrl+U: Delete from cursor to start of line
pub trait State {
    /// The status of the prompt.
    fn status(&self) -> Status;

    /// A mutable reference to the status of the prompt.
    fn status_mut(&mut self) -> &mut Status;

    /// A mutable reference to the focus state of the prompt.
    fn focus_state_mut(&mut self) -> &mut FocusState;

    /// The focus state of the prompt.
    fn focus_state(&self) -> FocusState;

    /// Sets the focus state of the prompt to [`Focus::Focused`].
    fn focus(&mut self) {
        *self.focus_state_mut() = FocusState::Focused;
    }

    /// Sets the focus state of the prompt to [`Focus::Unfocused`].
    fn blur(&mut self) {
        *self.focus_state_mut() = FocusState::Unfocused;
    }

    /// Whether the prompt is focused.
    fn is_focused(&self) -> bool {
        self.focus_state() == FocusState::Focused
    }

    /// The position of the cursor in the prompt.
    fn position(&self) -> usize;

    /// A mutable reference to the position of the cursor in the prompt.
    fn position_mut(&mut self) -> &mut usize;

    /// The cursor position of the prompt.
    fn cursor(&self) -> (u16, u16);

    /// A mutable reference to the cursor position of the prompt.
    fn cursor_mut(&mut self) -> &mut (u16, u16);

    /// The value of the prompt.
    fn value(&self) -> &str;

    /// A mutable reference to the value of the prompt.
    fn value_mut(&mut self) -> &mut String;

    fn len(&self) -> usize {
        self.value().chars().count()
    }

    fn is_empty(&self) -> bool {
        self.value().len() == 0
    }

    fn handle_key_event(&mut self, key_event: KeyEvent) {
        if key_event.kind == KeyEventKind::Release {
            return;
        }

        match (key_event.code, key_event.modifiers) {
            (KeyCode::Enter, _) => self.complete(),
            (KeyCode::Esc, _) | (KeyCode::Char('c'), KeyModifiers::CONTROL) => self.abort(),
            (KeyCode::Left, _) | (KeyCode::Char('b'), KeyModifiers::CONTROL) => self.move_left(),
            (KeyCode::Right, _) | (KeyCode::Char('f'), KeyModifiers::CONTROL) => self.move_right(),
            (KeyCode::Home, _) | (KeyCode::Char('a'), KeyModifiers::CONTROL) => self.move_start(),
            (KeyCode::End, _) | (KeyCode::Char('e'), KeyModifiers::CONTROL) => self.move_end(),
            (KeyCode::Backspace, _) | (KeyCode::Char('h'), KeyModifiers::CONTROL) => {
                self.backspace();
            }
            (KeyCode::Delete, _) | (KeyCode::Char('d'), KeyModifiers::CONTROL) => self.delete(),
            (KeyCode::Char('k'), KeyModifiers::CONTROL) => self.kill(),
            (KeyCode::Char('u'), KeyModifiers::CONTROL) => self.truncate(),
            (KeyCode::Char(c), KeyModifiers::NONE | KeyModifiers::SHIFT) => self.push(c),
            _ => {}
        }
    }

    fn complete(&mut self) {
        *self.status_mut() = Status::Done;
    }

    fn abort(&mut self) {
        *self.status_mut() = Status::Aborted;
    }

    fn delete(&mut self) {
        let position = self.position();
        if position == self.len() {
            return;
        }
        *self.value_mut() = chain!(
            self.value().chars().take(position),
            self.value().chars().skip(position + 1)
        )
        .collect();
    }

    fn backspace(&mut self) {
        let position = self.position();
        if position == 0 {
            return;
        }
        *self.value_mut() = chain!(
            self.value().chars().take(position.saturating_sub(1)),
            self.value().chars().skip(position)
        )
        .collect();
        *self.position_mut() = position.saturating_sub(1);
    }

    fn move_right(&mut self) {
        if self.position() == self.len() {
            return;
        }
        *self.position_mut() = self.position().saturating_add(1);
    }

    fn move_left(&mut self) {
        *self.position_mut() = self.position().saturating_sub(1);
    }

    fn move_end(&mut self) {
        *self.position_mut() = self.len();
    }

    fn move_start(&mut self) {
        *self.position_mut() = 0;
    }

    fn kill(&mut self) {
        let position = self.position();
        self.value_mut().truncate(position);
    }

    fn truncate(&mut self) {
        self.value_mut().clear();
        *self.position_mut() = 0;
    }

    fn push(&mut self, c: char) {
        if self.position() == self.len() {
            self.value_mut().push(c);
        } else {
            // We cannot use String::insert() as it operates on bytes, which can lead to incorrect modifications with
            // multibyte characters. Instead, we handle text manipulation at the character level using Rust's char type
            // for Unicode correctness. Check docs of String::insert() and String::chars() for futher info.
            *self.value_mut() = chain![
                self.value().chars().take(self.position()),
                once(c),
                self.value().chars().skip(self.position())
            ]
            .collect();
        }
        *self.position_mut() = self.position().saturating_add(1);
    }
}

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

    #[test]
    fn status_symbols() {
        assert_eq!(Status::Pending.symbol(), "?".cyan());
        assert_eq!(Status::Aborted.symbol(), "✘".red());
        assert_eq!(Status::Done.symbol(), "✔".green());
    }
}