dotstate 0.3.3

A modern, secure, and user-friendly dotfile manager built with Rust
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
use crate::keymap::Action;
use crossterm::event::{KeyCode, KeyModifiers};

/// A text input field with encapsulated state.
///
/// This struct wraps the text and cursor position, providing a cleaner API
/// for managing text input in forms and screens.
///
/// # Example
/// ```
/// use dotstate::utils::text_input::TextInput;
///
/// let mut input = TextInput::new();
/// input.insert_char('h');
/// input.insert_char('i');
/// assert_eq!(input.text(), "hi");
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TextInput {
    text: String,
    cursor: usize,
}

impl TextInput {
    /// Create a new empty text input.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a text input with initial text.
    pub fn with_text(text: impl Into<String>) -> Self {
        let text = text.into();
        let cursor = text.chars().count();
        Self { text, cursor }
    }

    /// Get the current text as a string slice.
    #[must_use]
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Get the current cursor position.
    #[must_use]
    pub fn cursor(&self) -> usize {
        self.cursor
    }

    /// Get the trimmed text.
    #[must_use]
    pub fn text_trimmed(&self) -> &str {
        self.text.trim()
    }

    /// Check if the text is empty (ignoring whitespace).
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.text.trim().is_empty()
    }

    /// Set the text and move cursor to end.
    pub fn set_text(&mut self, text: impl Into<String>) {
        self.text = text.into();
        self.cursor = self.text.chars().count();
    }

    /// Clear the text and reset cursor.
    pub fn clear(&mut self) {
        self.text.clear();
        self.cursor = 0;
    }

    /// Insert a character at the cursor position.
    pub fn insert_char(&mut self, c: char) {
        handle_char_insertion(&mut self.text, &mut self.cursor, c);
    }

    /// Delete the character before the cursor (backspace).
    pub fn backspace(&mut self) {
        handle_backspace(&mut self.text, &mut self.cursor);
    }

    /// Delete the character at the cursor position.
    pub fn delete(&mut self) {
        handle_delete(&mut self.text, &mut self.cursor);
    }

    /// Move the cursor left.
    pub fn move_left(&mut self) {
        if self.cursor > 0 {
            self.cursor -= 1;
        }
    }

    /// Move the cursor right.
    pub fn move_right(&mut self) {
        let char_count = self.text.chars().count();
        if self.cursor < char_count {
            self.cursor += 1;
        }
    }

    /// Move the cursor to the start.
    pub fn move_home(&mut self) {
        self.cursor = 0;
    }

    /// Move the cursor to the end.
    pub fn move_end(&mut self) {
        self.cursor = self.text.chars().count();
    }

    /// Handle a key code event.
    ///
    /// Returns true if the key was handled.
    pub fn handle_key(&mut self, key_code: KeyCode) -> bool {
        handle_input(&mut self.text, &mut self.cursor, key_code);
        matches!(
            key_code,
            KeyCode::Char(_)
                | KeyCode::Backspace
                | KeyCode::Delete
                | KeyCode::Left
                | KeyCode::Right
                | KeyCode::Home
                | KeyCode::End
        )
    }

    /// Handle an action from the keymap.
    ///
    /// Returns true if the action was handled.
    pub fn handle_action(&mut self, action: Action) -> bool {
        match action {
            Action::MoveLeft => {
                self.move_left();
                true
            }
            Action::MoveRight => {
                self.move_right();
                true
            }
            Action::Home => {
                self.move_home();
                true
            }
            Action::End => {
                self.move_end();
                true
            }
            Action::Backspace => {
                self.backspace();
                true
            }
            Action::DeleteChar => {
                self.delete();
                true
            }
            _ => false,
        }
    }

    /// Handle a key event with modifiers and action mapping.
    ///
    /// This is useful when you want to handle both raw keys and mapped actions.
    /// Regular characters are inserted directly, while special keys go through
    /// action mapping if available.
    pub fn handle_key_with_action(
        &mut self,
        key_code: KeyCode,
        _modifiers: KeyModifiers,
        action: Option<Action>,
    ) -> bool {
        // Try action first
        if let Some(action) = action {
            if self.handle_action(action) {
                return true;
            }
        }

        // Fall back to raw key handling
        self.handle_key(key_code)
    }
    /// Check if an action is safe to process when a text input is focused.
    ///
    /// Returns true if the action is "safe" (like navigation or text editing) and should
    /// be processed even when the input has focus.
    /// Returns false if the action should be suppressed (like 'Quit' bound to 'q') so that
    /// the key can be treated as text input.
    #[must_use]
    pub fn is_action_allowed_when_focused(action: &Action) -> bool {
        matches!(
            action,
            // Navigation between fields or exiting input
            Action::Cancel          // Esc
            | Action::Confirm       // Enter
            | Action::NextTab       // Tab
            | Action::PrevTab       // Shift+Tab
            // Text editing actions
            | Action::MoveLeft
            | Action::MoveRight
            | Action::Home
            | Action::End
            | Action::Backspace
            | Action::DeleteChar
        )
    }
}

/// Handle text input for a single character insertion
///
/// # Arguments
/// * `text` - Mutable reference to the text string
/// * `cursor_pos` - Mutable reference to cursor position
/// * `c` - Character to insert
fn handle_char_insertion(text: &mut String, cursor_pos: &mut usize, c: char) {
    if c.is_ascii() && !c.is_control() {
        let byte_index = text
            .char_indices()
            .map(|(i, _)| i)
            .nth(*cursor_pos)
            .unwrap_or(text.len());
        text.insert(byte_index, c);
        *cursor_pos = (*cursor_pos + 1).min(text.chars().count());
    }
}

/// Handle cursor movement
///
/// # Arguments
/// * `text` - The text string
/// * `cursor_pos` - Mutable reference to cursor position
/// * `key_code` - Key code (Left, Right, Home, End)
fn handle_cursor_movement(text: &str, cursor_pos: &mut usize, key_code: KeyCode) {
    match key_code {
        KeyCode::Left if *cursor_pos > 0 => {
            *cursor_pos -= 1;
        }
        KeyCode::Right => {
            let char_count = text.chars().count();
            if *cursor_pos < char_count {
                *cursor_pos += 1;
            }
        }
        KeyCode::Home => {
            *cursor_pos = 0;
        }
        KeyCode::End => {
            *cursor_pos = text.chars().count();
        }
        _ => {}
    }
}

/// Handle character deletion (backspace)
///
/// # Arguments
/// * `text` - Mutable reference to the text string
/// * `cursor_pos` - Mutable reference to cursor position
fn handle_backspace(text: &mut String, cursor_pos: &mut usize) {
    if *cursor_pos > 0 {
        let before_cursor = text.chars().take(*cursor_pos - 1);
        let after_cursor = text.chars().skip(*cursor_pos);
        *text = before_cursor.chain(after_cursor).collect();
        *cursor_pos -= 1;
    }
}

/// Handle character deletion (delete key)
///
/// # Arguments
/// * `text` - Mutable reference to the text string
/// * `cursor_pos` - Mutable reference to cursor position
fn handle_delete(text: &mut String, cursor_pos: &mut usize) {
    let char_count = text.chars().count();
    if *cursor_pos < char_count {
        let before_cursor = text.chars().take(*cursor_pos);
        let after_cursor = text.chars().skip(*cursor_pos + 1);
        *text = before_cursor.chain(after_cursor).collect();
    }
}
/// Handle generic input for text fields (movement, editing)
///
/// # Arguments
/// * `text` - Mutable reference to the text string
/// * `cursor_pos` - Mutable reference to cursor position
/// * `key_code` - Key code from event
fn handle_input(text: &mut String, cursor_pos: &mut usize, key_code: KeyCode) {
    match key_code {
        KeyCode::Char(c) => handle_char_insertion(text, cursor_pos, c),
        KeyCode::Backspace => handle_backspace(text, cursor_pos),
        KeyCode::Delete => handle_delete(text, cursor_pos),
        KeyCode::Left | KeyCode::Right | KeyCode::Home | KeyCode::End => {
            handle_cursor_movement(text, cursor_pos, key_code);
        }
        _ => {}
    }
}

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

    #[test]
    fn test_char_insertion() {
        let mut text = String::from("hello");
        let mut cursor = 2;

        handle_char_insertion(&mut text, &mut cursor, 'x');
        assert_eq!(text, "hexllo");
        assert_eq!(cursor, 3);
    }

    #[test]
    fn test_char_insertion_at_end() {
        let mut text = String::from("hello");
        let mut cursor = 5;

        handle_char_insertion(&mut text, &mut cursor, '!');
        assert_eq!(text, "hello!");
        assert_eq!(cursor, 6);
    }

    #[test]
    fn test_cursor_movement_left() {
        let text = "hello";
        let mut cursor = 3;

        handle_cursor_movement(text, &mut cursor, KeyCode::Left);
        assert_eq!(cursor, 2);
    }

    #[test]
    fn test_cursor_movement_right() {
        let text = "hello";
        let mut cursor = 2;

        handle_cursor_movement(text, &mut cursor, KeyCode::Right);
        assert_eq!(cursor, 3);
    }

    #[test]
    fn test_cursor_movement_home() {
        let text = "hello";
        let mut cursor = 3;

        handle_cursor_movement(text, &mut cursor, KeyCode::Home);
        assert_eq!(cursor, 0);
    }

    #[test]
    fn test_cursor_movement_end() {
        let text = "hello";
        let mut cursor = 2;

        handle_cursor_movement(text, &mut cursor, KeyCode::End);
        assert_eq!(cursor, 5);
    }

    #[test]
    fn test_backspace() {
        let mut text = String::from("hello");
        let mut cursor = 3;

        handle_backspace(&mut text, &mut cursor);
        assert_eq!(text, "helo"); // Deletes 'l' at position 2
        assert_eq!(cursor, 2);
    }

    #[test]
    fn test_backspace_at_start() {
        let mut text = String::from("hello");
        let mut cursor = 0;

        handle_backspace(&mut text, &mut cursor);
        assert_eq!(text, "hello"); // No change
        assert_eq!(cursor, 0);
    }

    #[test]
    fn test_delete() {
        let mut text = String::from("hello");
        let mut cursor = 2;

        handle_delete(&mut text, &mut cursor);
        assert_eq!(text, "helo");
        assert_eq!(cursor, 2); // Cursor doesn't move
    }

    #[test]
    fn test_delete_at_end() {
        let mut text = String::from("hello");
        let mut cursor = 5;

        handle_delete(&mut text, &mut cursor);
        assert_eq!(text, "hello"); // No change
        assert_eq!(cursor, 5);
    }

    #[test]
    fn test_unicode_handling() {
        let mut text = String::from("héllo");
        let mut cursor = 2;

        handle_char_insertion(&mut text, &mut cursor, 'x');
        assert_eq!(text, "héxllo");
        assert_eq!(cursor, 3);
    }

    // TextInput struct tests
    #[test]
    fn test_text_input_new() {
        let input = TextInput::new();
        assert_eq!(input.text(), "");
        assert_eq!(input.cursor(), 0);
        assert!(input.is_empty());
    }

    #[test]
    fn test_text_input_with_text() {
        let input = TextInput::with_text("hello");
        assert_eq!(input.text(), "hello");
        assert_eq!(input.cursor(), 5);
        assert!(!input.is_empty());
    }

    #[test]
    fn test_text_input_set_text() {
        let mut input = TextInput::new();
        input.set_text("world");
        assert_eq!(input.text(), "world");
        assert_eq!(input.cursor(), 5);
    }

    #[test]
    fn test_text_input_clear() {
        let mut input = TextInput::with_text("hello");
        input.clear();
        assert_eq!(input.text(), "");
        assert_eq!(input.cursor(), 0);
        assert!(input.is_empty());
    }

    #[test]
    fn test_text_input_insert_char() {
        let mut input = TextInput::new();
        input.insert_char('h');
        input.insert_char('i');
        assert_eq!(input.text(), "hi");
        assert_eq!(input.cursor(), 2);
    }

    #[test]
    fn test_text_input_backspace() {
        let mut input = TextInput::with_text("hello");
        input.backspace();
        assert_eq!(input.text(), "hell");
        assert_eq!(input.cursor(), 4);
    }

    #[test]
    fn test_text_input_delete() {
        let mut input = TextInput::with_text("hello");
        input.move_home();
        input.delete();
        assert_eq!(input.text(), "ello");
        assert_eq!(input.cursor(), 0);
    }

    #[test]
    fn test_text_input_cursor_movement() {
        let mut input = TextInput::with_text("hello");

        input.move_home();
        assert_eq!(input.cursor(), 0);

        input.move_right();
        assert_eq!(input.cursor(), 1);

        input.move_left();
        assert_eq!(input.cursor(), 0);

        input.move_end();
        assert_eq!(input.cursor(), 5);
    }

    #[test]
    fn test_text_input_handle_key() {
        let mut input = TextInput::new();

        assert!(input.handle_key(KeyCode::Char('a')));
        assert_eq!(input.text(), "a");

        assert!(input.handle_key(KeyCode::Char('b')));
        assert_eq!(input.text(), "ab");

        assert!(input.handle_key(KeyCode::Backspace));
        assert_eq!(input.text(), "a");
    }

    #[test]
    fn test_text_input_handle_action() {
        let mut input = TextInput::with_text("hello");

        assert!(input.handle_action(Action::Home));
        assert_eq!(input.cursor(), 0);

        assert!(input.handle_action(Action::MoveRight));
        assert_eq!(input.cursor(), 1);

        assert!(input.handle_action(Action::DeleteChar));
        assert_eq!(input.text(), "hllo");
    }

    #[test]
    fn test_text_input_trimmed() {
        let input = TextInput::with_text("  hello  ");
        assert_eq!(input.text_trimmed(), "hello");
        assert!(!input.is_empty());
    }

    #[test]
    fn test_text_input_is_empty_whitespace() {
        let input = TextInput::with_text("   ");
        assert!(input.is_empty());
    }

    #[test]
    fn test_text_input_clone() {
        let input1 = TextInput::with_text("hello");
        let input2 = input1.clone();

        assert_eq!(input1.text(), input2.text());
        assert_eq!(input1.cursor(), input2.cursor());
    }

    #[test]
    fn test_text_input_default() {
        let input: TextInput = Default::default();
        assert_eq!(input.text(), "");
        assert_eq!(input.cursor(), 0);
    }
    #[test]
    fn test_is_action_allowed_when_focused() {
        // Allowed actions
        assert!(TextInput::is_action_allowed_when_focused(&Action::Cancel));
        assert!(TextInput::is_action_allowed_when_focused(&Action::Confirm));
        assert!(TextInput::is_action_allowed_when_focused(&Action::NextTab));
        assert!(TextInput::is_action_allowed_when_focused(
            &Action::Backspace
        ));
        assert!(TextInput::is_action_allowed_when_focused(&Action::MoveLeft));

        // Blocked actions (should be suppressed for typing)
        assert!(!TextInput::is_action_allowed_when_focused(&Action::Quit));
        assert!(!TextInput::is_action_allowed_when_focused(&Action::Help));
        assert!(!TextInput::is_action_allowed_when_focused(&Action::Delete)); // List delete
        assert!(!TextInput::is_action_allowed_when_focused(&Action::Edit));
    }
}