devbook-tui 1.1.0

A fast, keyboard-driven terminal user interface for Devbook prompt engineering workbench
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
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputMode {
    Normal,
    Insert,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PendingOp {
    Delete,
    Replace,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputAction {
    /// Input handled internally (text or cursor or mode changed)
    Consumed,
    /// User pressed Esc while already in Normal mode (e.g., close modal)
    Cancel,
    /// User pressed Enter (e.g., submit modal)
    Submit,
    /// Key was not handled by TextInput (e.g., Tab, Up/Down)
    Ignored,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TextInput {
    pub value: String,
    pub cursor: usize, // char index
    pub mode: InputMode,
    pub pending_op: Option<PendingOp>,
}

impl Default for TextInput {
    fn default() -> Self {
        Self::new("")
    }
}

impl TextInput {
    pub fn new(initial: impl Into<String>) -> Self {
        let value = initial.into();
        let cursor = value.chars().count();
        Self {
            value,
            cursor,
            mode: InputMode::Insert,
            pending_op: None,
        }
    }

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

    fn byte_index(&self, char_idx: usize) -> usize {
        self.value
            .char_indices()
            .nth(char_idx)
            .map(|(i, _)| i)
            .unwrap_or(self.value.len())
    }

    fn clamp_cursor(&mut self) {
        let len = self.char_len();
        match self.mode {
            InputMode::Insert => {
                if self.cursor > len {
                    self.cursor = len;
                }
            }
            InputMode::Normal => {
                if len == 0 {
                    self.cursor = 0;
                } else if self.cursor >= len {
                    self.cursor = len - 1;
                }
            }
        }
    }

    fn next_word_pos(&self) -> usize {
        let chars: Vec<char> = self.value.chars().collect();
        let len = chars.len();
        if self.cursor >= len {
            return len;
        }
        let mut i = self.cursor;
        let is_word = |c: char| c.is_alphanumeric() || c == '_';
        if is_word(chars[i]) {
            while i < len && is_word(chars[i]) {
                i += 1;
            }
        } else if !chars[i].is_whitespace() {
            while i < len && !is_word(chars[i]) && !chars[i].is_whitespace() {
                i += 1;
            }
        }
        while i < len && chars[i].is_whitespace() {
            i += 1;
        }
        i
    }

    fn prev_word_pos(&self) -> usize {
        let chars: Vec<char> = self.value.chars().collect();
        if self.cursor == 0 || chars.is_empty() {
            return 0;
        }
        let mut i = self.cursor.min(chars.len());
        let is_word = |c: char| c.is_alphanumeric() || c == '_';
        i = i.saturating_sub(1);
        while i > 0 && chars[i].is_whitespace() {
            i -= 1;
        }
        if is_word(chars[i]) {
            while i > 0 && is_word(chars[i - 1]) {
                i -= 1;
            }
        } else if !chars[i].is_whitespace() {
            while i > 0 && !is_word(chars[i - 1]) && !chars[i - 1].is_whitespace() {
                i -= 1;
            }
        }
        i
    }

    fn delete_range(&mut self, start_char: usize, end_char: usize) {
        if start_char >= end_char {
            return;
        }
        let start_b = self.byte_index(start_char);
        let end_b = self.byte_index(end_char);
        self.value.replace_range(start_b..end_b, "");
        self.cursor = start_char;
        self.clamp_cursor();
    }

    pub fn handle_key(&mut self, key: KeyEvent) -> InputAction {
        if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
            return InputAction::Cancel;
        }

        match self.mode {
            InputMode::Insert => self.handle_insert(key),
            InputMode::Normal => self.handle_normal(key),
        }
    }

    fn handle_insert(&mut self, key: KeyEvent) -> InputAction {
        match key.code {
            KeyCode::Esc => {
                self.mode = InputMode::Normal;
                self.pending_op = None;
                self.cursor = self.cursor.saturating_sub(1);
                self.clamp_cursor();
                InputAction::Consumed
            }
            KeyCode::Enter => InputAction::Submit,
            KeyCode::Left => {
                self.cursor = self.cursor.saturating_sub(1);
                InputAction::Consumed
            }
            KeyCode::Right => {
                let len = self.char_len();
                if self.cursor < len {
                    self.cursor += 1;
                }
                InputAction::Consumed
            }
            KeyCode::Home => {
                self.cursor = 0;
                InputAction::Consumed
            }
            KeyCode::End => {
                self.cursor = self.char_len();
                InputAction::Consumed
            }
            KeyCode::Backspace => {
                if self.cursor > 0 {
                    let start = self.byte_index(self.cursor - 1);
                    let end = self.byte_index(self.cursor);
                    self.value.replace_range(start..end, "");
                    self.cursor -= 1;
                }
                InputAction::Consumed
            }
            KeyCode::Delete => {
                let len = self.char_len();
                if self.cursor < len {
                    let start = self.byte_index(self.cursor);
                    let end = self.byte_index(self.cursor + 1);
                    self.value.replace_range(start..end, "");
                }
                InputAction::Consumed
            }
            KeyCode::Char(c) => {
                let idx = self.byte_index(self.cursor);
                self.value.insert(idx, c);
                self.cursor += 1;
                InputAction::Consumed
            }
            _ => InputAction::Ignored,
        }
    }

    fn handle_normal(&mut self, key: KeyEvent) -> InputAction {
        if let Some(op) = self.pending_op.take() {
            match op {
                PendingOp::Replace => {
                    if let KeyCode::Char(c) = key.code {
                        let len = self.char_len();
                        if self.cursor < len {
                            let start = self.byte_index(self.cursor);
                            let end = self.byte_index(self.cursor + 1);
                            let mut buf = [0u8; 4];
                            let s = c.encode_utf8(&mut buf);
                            self.value.replace_range(start..end, s);
                        }
                        return InputAction::Consumed;
                    }
                    return InputAction::Consumed;
                }
                PendingOp::Delete => {
                    match key.code {
                        KeyCode::Char('d') => {
                            self.value.clear();
                            self.cursor = 0;
                        }
                        KeyCode::Char('w') => {
                            let end = self.next_word_pos();
                            self.delete_range(self.cursor, end);
                        }
                        KeyCode::Char('b') => {
                            let start = self.prev_word_pos();
                            self.delete_range(start, self.cursor);
                        }
                        KeyCode::Char('$') | KeyCode::End => {
                            let len = self.char_len();
                            self.delete_range(self.cursor, len);
                        }
                        KeyCode::Char('0') | KeyCode::Home => {
                            self.delete_range(0, self.cursor);
                        }
                        _ => {}
                    }
                    return InputAction::Consumed;
                }
            }
        }

        match key.code {
            KeyCode::Esc => InputAction::Cancel,
            KeyCode::Enter => InputAction::Submit,
            // Mode switching
            KeyCode::Char('i') => {
                self.mode = InputMode::Insert;
                InputAction::Consumed
            }
            KeyCode::Char('a') => {
                self.mode = InputMode::Insert;
                let len = self.char_len();
                if self.cursor < len {
                    self.cursor += 1;
                }
                InputAction::Consumed
            }
            KeyCode::Char('I') => {
                self.mode = InputMode::Insert;
                self.cursor = 0;
                InputAction::Consumed
            }
            KeyCode::Char('A') => {
                self.mode = InputMode::Insert;
                self.cursor = self.char_len();
                InputAction::Consumed
            }
            // Navigation
            KeyCode::Char('h') | KeyCode::Left => {
                self.cursor = self.cursor.saturating_sub(1);
                InputAction::Consumed
            }
            KeyCode::Char('l') | KeyCode::Right => {
                let len = self.char_len();
                if len > 0 && self.cursor + 1 < len {
                    self.cursor += 1;
                }
                InputAction::Consumed
            }
            KeyCode::Char('0') | KeyCode::Home => {
                self.cursor = 0;
                InputAction::Consumed
            }
            KeyCode::Char('$') | KeyCode::End => {
                let len = self.char_len();
                self.cursor = len.saturating_sub(1);
                InputAction::Consumed
            }
            KeyCode::Char('w') => {
                let next = self.next_word_pos();
                let len = self.char_len();
                self.cursor = if len == 0 { 0 } else { next.min(len - 1) };
                InputAction::Consumed
            }
            KeyCode::Char('b') => {
                self.cursor = self.prev_word_pos();
                InputAction::Consumed
            }
            // Editing
            KeyCode::Char('x') | KeyCode::Delete => {
                let len = self.char_len();
                if self.cursor < len {
                    self.delete_range(self.cursor, self.cursor + 1);
                }
                InputAction::Consumed
            }
            KeyCode::Char('r') => {
                self.pending_op = Some(PendingOp::Replace);
                InputAction::Consumed
            }
            KeyCode::Char('D') => {
                let len = self.char_len();
                self.delete_range(self.cursor, len);
                InputAction::Consumed
            }
            KeyCode::Char('d') => {
                self.pending_op = Some(PendingOp::Delete);
                InputAction::Consumed
            }
            _ => InputAction::Ignored,
        }
    }
}

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

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

    #[test]
    fn test_insert_and_cursor_navigation() {
        let mut ti = TextInput::new("helo");
        assert_eq!(ti.cursor, 4);
        ti.handle_key(key(KeyCode::Left));
        ti.handle_key(key(KeyCode::Left));
        assert_eq!(ti.cursor, 2);
        ti.handle_key(key(KeyCode::Char('l')));
        assert_eq!(ti.value, "hello");
        assert_eq!(ti.cursor, 3);
        ti.handle_key(key(KeyCode::Home));
        assert_eq!(ti.cursor, 0);
        ti.handle_key(key(KeyCode::Delete));
        assert_eq!(ti.value, "ello");
        ti.handle_key(key(KeyCode::End));
        assert_eq!(ti.cursor, 4);
        ti.handle_key(key(KeyCode::Backspace));
        assert_eq!(ti.value, "ell");
    }

    #[test]
    fn test_vim_modes_and_motions() {
        let mut ti = TextInput::new("one two three");
        ti.handle_key(key(KeyCode::Esc));
        assert_eq!(ti.mode, InputMode::Normal);
        assert_eq!(ti.cursor, 12);

        ti.handle_key(key(KeyCode::Char('0')));
        assert_eq!(ti.cursor, 0);

        ti.handle_key(key(KeyCode::Char('w')));
        assert_eq!(ti.cursor, 4); // 't' in "two"

        ti.handle_key(key(KeyCode::Char('w')));
        assert_eq!(ti.cursor, 8); // 't' in "three"

        ti.handle_key(key(KeyCode::Char('b')));
        assert_eq!(ti.cursor, 4);

        ti.handle_key(key(KeyCode::Char('$')));
        assert_eq!(ti.cursor, 12);

        ti.handle_key(key(KeyCode::Char('h')));
        assert_eq!(ti.cursor, 11);

        ti.handle_key(key(KeyCode::Char('l')));
        assert_eq!(ti.cursor, 12);
    }

    #[test]
    fn test_vim_normal_editing() {
        let mut ti = TextInput::new("alpha beta gamma");
        ti.handle_key(key(KeyCode::Esc));
        ti.handle_key(key(KeyCode::Char('0')));

        // x deletes char under cursor
        ti.handle_key(key(KeyCode::Char('x')));
        assert_eq!(ti.value, "lpha beta gamma");

        // r replaces char under cursor
        ti.handle_key(key(KeyCode::Char('r')));
        ti.handle_key(key(KeyCode::Char('A')));
        assert_eq!(ti.value, "Apha beta gamma");

        // dw deletes word forward
        ti.handle_key(key(KeyCode::Char('d')));
        ti.handle_key(key(KeyCode::Char('w')));
        assert_eq!(ti.value, "beta gamma");

        // d$ deletes to end of line
        ti.handle_key(key(KeyCode::Char('w'))); // at 'g'
        ti.handle_key(key(KeyCode::Char('d')));
        ti.handle_key(key(KeyCode::Char('$')));
        assert_eq!(ti.value, "beta ");

        // dd clears line
        ti.handle_key(key(KeyCode::Char('d')));
        ti.handle_key(key(KeyCode::Char('d')));
        assert_eq!(ti.value, "");
        assert_eq!(ti.cursor, 0);
    }

    #[test]
    fn test_vim_db_and_d0_and_d() {
        let mut ti = TextInput::new("one two three");
        ti.handle_key(key(KeyCode::Esc));
        ti.handle_key(key(KeyCode::Char('0')));
        ti.handle_key(key(KeyCode::Char('w'))); // at 't' in two (4)
        ti.handle_key(key(KeyCode::Char('w'))); // at 't' in three (8)
        ti.handle_key(key(KeyCode::Char('d')));
        ti.handle_key(key(KeyCode::Char('b')));
        assert_eq!(ti.value, "one three");
        assert_eq!(ti.cursor, 4);

        ti.handle_key(key(KeyCode::Char('D')));
        assert_eq!(ti.value, "one ");

        ti.handle_key(key(KeyCode::Char('d')));
        ti.handle_key(key(KeyCode::Char('0')));
        assert_eq!(ti.value, " ");
    }
}