promkit-widgets 0.6.1

Widgets for promkit
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
use std::collections::HashSet;

use promkit_core::grapheme::{StyledGrapheme, StyledGraphemes};

use crate::cursor::Cursor;

/// Edit mode.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Default)]
pub enum Mode {
    #[default]
    /// Insert a char at the current position.
    Insert,
    /// Overwrite a char at the current position.
    Overwrite,
}

/// A text editor that supports basic editing operations
/// such as insert, delete, and overwrite.
/// It utilizes a cursor to navigate and manipulate the text.
#[derive(Clone)]
pub struct TextEditor(Cursor<StyledGraphemes>);

impl Default for TextEditor {
    fn default() -> Self {
        Self(Cursor::new(
            // Set cursor
            StyledGraphemes::from(" "),
            0,
            false,
        ))
    }
}

impl TextEditor {
    pub fn new<S: AsRef<str>>(s: S) -> Self {
        let mut buf = s.as_ref().to_owned();
        buf.push(' ');
        let pos = buf.len() - 1;
        Self(Cursor::new(StyledGraphemes::from(buf), pos, false))
    }

    /// Returns the current text including the cursor.
    pub fn text(&self) -> StyledGraphemes {
        self.0.contents().clone()
    }

    /// Returns the text without the cursor.
    pub fn text_without_cursor(&self) -> StyledGraphemes {
        let mut ret = self.text();
        ret.pop_back();
        ret
    }

    /// Returns the current position of the cursor within the text.
    pub fn position(&self) -> usize {
        self.0.position()
    }

    /// Masks all characters except the cursor with the specified mask character.
    pub fn masking(&self, mask: char) -> StyledGraphemes {
        self.text()
            .chars()
            .into_iter()
            .enumerate()
            .map(|(i, c)| StyledGrapheme::from(if i == self.text().len() - 1 { c } else { mask }))
            .collect::<StyledGraphemes>()
    }

    /// Replaces the current text with new text and positions the cursor at the end.
    pub fn replace(&mut self, new: &str) {
        let mut buf = new.to_owned();
        buf.push(' ');
        let pos = buf.len() - 1;
        *self = Self(Cursor::new(StyledGraphemes::from(buf), pos, false));
    }

    /// Inserts a character at the current cursor position.
    pub fn insert(&mut self, ch: char) {
        let pos = self.position();
        self.0.contents_mut().insert(pos, StyledGrapheme::from(ch));
        self.forward();
    }

    pub fn insert_chars(&mut self, vch: &Vec<char>) {
        for ch in vch {
            self.insert(*ch);
        }
    }

    /// Overwrites the character at the current cursor position with the specified character.
    pub fn overwrite(&mut self, ch: char) {
        if self.0.is_tail() {
            self.insert(ch)
        } else {
            let pos = self.position();
            self.0
                .contents_mut()
                .replace_range(pos..pos + 1, ch.to_string());
            self.forward();
        }
    }

    pub fn overwrite_chars(&mut self, vch: &Vec<char>) {
        for ch in vch {
            self.overwrite(*ch);
        }
    }

    /// Erases the character before the cursor position.
    pub fn erase(&mut self) {
        if !self.0.is_head() {
            self.backward();
            let pos = self.position();
            self.0.contents_mut().drain(pos..pos + 1);
        }
    }

    /// Clears all text and resets the editor to its default state.
    pub fn erase_all(&mut self) {
        *self = Self::default();
    }

    /// Erases the text from the current cursor position to the specified position,
    /// considering whether pos is greater or smaller than the current position.
    fn erase_to_position(&mut self, pos: usize) {
        let current_pos = self.position();
        if pos > current_pos {
            self.0.contents_mut().drain(current_pos..pos);
        } else {
            self.0.contents_mut().drain(pos..current_pos);
            self.0.move_to(pos);
        }
    }

    /// Finds the nearest previous index of any character in `word_break_chars` from the cursor position.
    fn find_previous_nearest_index(&self, word_break_chars: &HashSet<char>) -> usize {
        let current_position = self.position();
        self.text()
            .chars()
            .iter()
            .enumerate()
            .filter(|&(i, _)| i < current_position.saturating_sub(1))
            .rev()
            .find(|&(_, c)| word_break_chars.contains(c))
            .map(|(i, _)| i + 1)
            .unwrap_or(0)
    }

    /// Erases the text from the current cursor position to the nearest previous character in `word_break_chars`.
    pub fn erase_to_previous_nearest(&mut self, word_break_chars: &HashSet<char>) {
        let pos = self.find_previous_nearest_index(word_break_chars);
        self.erase_to_position(pos);
    }

    /// Moves the cursor to the nearest previous character in `word_break_chars`.
    pub fn move_to_previous_nearest(&mut self, word_break_chars: &HashSet<char>) {
        let pos = self.find_previous_nearest_index(word_break_chars);
        self.0.move_to(pos);
    }

    /// Finds the nearest next index of any character in `word_break_chars` from the cursor position.
    fn find_next_nearest_index(&self, word_break_chars: &HashSet<char>) -> usize {
        let current_position = self.position();
        self.text()
            .chars()
            .iter()
            .enumerate()
            .filter(|&(i, _)| i > current_position)
            .find(|&(_, c)| word_break_chars.contains(c))
            .map(|(i, _)| {
                if i < self.0.contents().len() - 1 {
                    i + 1
                } else {
                    self.0.contents().len() - 1
                }
            })
            .unwrap_or(self.0.contents().len() - 1)
    }

    /// Erases the text from the current cursor position to the nearest next character in `word_break_chars`.
    pub fn erase_to_next_nearest(&mut self, word_break_chars: &HashSet<char>) {
        let pos = self.find_next_nearest_index(word_break_chars);
        self.erase_to_position(pos);
    }

    /// Moves the cursor to the nearest next character in `word_break_chars`.
    pub fn move_to_next_nearest(&mut self, word_break_chars: &HashSet<char>) {
        let pos = self.find_next_nearest_index(word_break_chars);
        self.0.move_to(pos);
    }

    /// Moves the cursor to the beginning of the text.
    pub fn move_to_head(&mut self) {
        self.0.move_to_head()
    }

    /// Moves the cursor to the end of the text.
    pub fn move_to_tail(&mut self) {
        self.0.move_to_tail()
    }

    pub fn shift(&mut self, backward: usize, forward: usize) -> bool {
        self.0.shift(backward, forward)
    }

    /// Moves the cursor one position backward, if possible.
    pub fn backward(&mut self) -> bool {
        self.0.backward()
    }

    /// Moves the cursor one position forward, if possible.
    pub fn forward(&mut self) -> bool {
        self.0.forward()
    }
}

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

    fn new_with_position(s: String, p: usize) -> TextEditor {
        TextEditor(Cursor::new(StyledGraphemes::from(s), p, false))
    }

    mod masking {
        use super::*;

        #[test]
        fn test() {
            let txt = new_with_position(String::from("abcde "), 0);
            assert_eq!(StyledGraphemes::from("***** "), txt.masking('*'))
        }
    }

    mod erase {
        use super::*;

        #[test]
        fn test_for_empty() {
            let txt = TextEditor::default();
            assert_eq!(StyledGraphemes::from(" "), txt.text());
            assert_eq!(0, txt.position());
        }

        #[test]
        fn test_at_non_edge() {
            let mut txt = new_with_position(
                String::from("abc "),
                1, // indicate `b`.
            );
            let new = new_with_position(
                String::from("bc "),
                0, // indicate `b`.
            );
            txt.erase();
            assert_eq!(new.text(), txt.text());
            assert_eq!(new.position(), txt.position());
        }

        #[test]
        fn test_at_tail() {
            let mut txt = new_with_position(
                String::from("abc "),
                3, // indicate tail.
            );
            let new = new_with_position(
                String::from("ab "),
                2, // indicate tail.
            );
            txt.erase();
            assert_eq!(new.text(), txt.text());
            assert_eq!(new.position(), txt.position());
        }

        #[test]
        fn test_at_head() {
            let txt = new_with_position(
                String::from("abc "),
                0, // indicate `a`.
            );
            assert_eq!(StyledGraphemes::from("abc "), txt.text());
            assert_eq!(0, txt.position());
        }
    }

    mod find_previous_nearest_index {
        use super::*;

        use std::collections::HashSet;

        #[test]
        fn test() {
            let mut txt = new_with_position(String::from("koko momo jojo "), 11); // indicate `o`.
            assert_eq!(10, txt.find_previous_nearest_index(&HashSet::from([' '])));
            txt.0.move_to(10);
            assert_eq!(5, txt.find_previous_nearest_index(&HashSet::from([' '])));
        }

        #[test]
        fn test_with_no_target() {
            let txt = new_with_position(String::from("koko momo jojo "), 7); // indicate `m`.
            assert_eq!(0, txt.find_previous_nearest_index(&HashSet::from(['z'])));
        }
    }

    mod find_next_nearest_index {
        use super::*;

        use std::collections::HashSet;

        #[test]
        fn test() {
            let mut txt = new_with_position(String::from("koko momo jojo "), 7); // indicate `m`.
            assert_eq!(10, txt.find_next_nearest_index(&HashSet::from([' '])));
            txt.0.move_to(10);
            assert_eq!(14, txt.find_next_nearest_index(&HashSet::from([' '])));
        }

        #[test]
        fn test_with_no_target() {
            let txt = new_with_position(String::from("koko momo jojo "), 7); // indicate `m`.
            assert_eq!(14, txt.find_next_nearest_index(&HashSet::from(['z'])));
        }
    }

    mod insert {
        use super::*;

        #[test]
        fn test_for_empty() {
            let mut txt = TextEditor::default();
            let new = new_with_position(
                String::from("d "),
                1, // indicate tail.
            );
            txt.insert('d');
            assert_eq!(new.text(), txt.text());
            assert_eq!(new.position(), txt.position());
        }

        #[test]
        fn test_at_non_edge() {
            let mut txt = new_with_position(
                String::from("abc "),
                1, // indicate `b`.
            );
            let new = new_with_position(
                String::from("adbc "),
                2, // indicate `b`.
            );
            txt.insert('d');
            assert_eq!(new.text(), txt.text());
            assert_eq!(new.position(), txt.position());
        }

        #[test]
        fn test_at_tail() {
            let mut txt = new_with_position(
                String::from("abc "),
                3, // indicate tail.
            );
            let new = new_with_position(
                String::from("abcd "),
                4, // indicate tail.
            );
            txt.insert('d');
            assert_eq!(new.text(), txt.text());
            assert_eq!(new.position(), txt.position());
        }

        #[test]
        fn test_at_head() {
            let mut txt = new_with_position(
                String::from("abc "),
                0, // indicate `a`.
            );
            let new = new_with_position(
                String::from("dabc "),
                1, // indicate `a`.
            );
            txt.insert('d');
            assert_eq!(new.text(), txt.text());
            assert_eq!(new.position(), txt.position());
        }
    }

    mod overwrite {
        use super::*;

        #[test]
        fn test_for_empty() {
            let mut txt = TextEditor::default();
            let new = new_with_position(
                String::from("d "),
                1, // indicate tail.
            );
            txt.overwrite('d');
            assert_eq!(new.text(), txt.text());
            assert_eq!(new.position(), txt.position());
        }

        #[test]
        fn test_at_non_edge() {
            let mut txt = new_with_position(
                String::from("abc "),
                1, // indicate `b`.
            );
            let new = new_with_position(
                String::from("adc "),
                2, // indicate `c`.
            );
            txt.overwrite('d');
            assert_eq!(new.text(), txt.text());
            assert_eq!(new.position(), txt.position());
        }

        #[test]
        fn test_at_tail() {
            let mut txt = new_with_position(
                String::from("abc "),
                3, // indicate tail.
            );
            let new = new_with_position(
                String::from("abcd "),
                4, // indicate tail.
            );
            txt.overwrite('d');
            assert_eq!(new.text(), txt.text());
            assert_eq!(new.position(), txt.position());
        }

        #[test]
        fn test_at_head() {
            let mut txt = new_with_position(
                String::from("abc "),
                0, // indicate `a`.
            );
            let new = new_with_position(
                String::from("dbc "),
                1, // indicate `b`.
            );
            txt.overwrite('d');
            assert_eq!(new.text(), txt.text());
            assert_eq!(new.position(), txt.position());
        }
    }

    mod backward {
        use super::*;

        #[test]
        fn test_for_empty() {
            let mut txt = TextEditor::default();
            txt.backward();
            assert_eq!(StyledGraphemes::from(" "), txt.text());
            assert_eq!(0, txt.position());
        }

        #[test]
        fn test_at_non_edge() {
            let mut txt = new_with_position(
                String::from("abc "),
                1, // indicate `b`.
            );
            let new = new_with_position(
                String::from("abc "),
                0, // indicate `a`.
            );
            txt.backward();
            assert_eq!(new.text(), txt.text());
            assert_eq!(new.position(), txt.position());
        }

        #[test]
        fn test_at_tail() {
            let mut txt = new_with_position(
                String::from("abc "),
                3, // indicate tail.
            );
            let new = new_with_position(
                String::from("abc "),
                2, // indicate `c`.
            );
            txt.backward();
            assert_eq!(new.text(), txt.text());
            assert_eq!(new.position(), txt.position());
        }

        #[test]
        fn test_at_head() {
            let mut txt = new_with_position(
                String::from("abc "),
                0, // indicate `a`.
            );
            txt.backward();
            assert_eq!(StyledGraphemes::from("abc "), txt.text());
            assert_eq!(0, txt.position());
        }
    }

    mod forward {
        use super::*;

        #[test]
        fn test_for_empty() {
            let mut txt = TextEditor::default();
            txt.forward();
            assert_eq!(StyledGraphemes::from(" "), txt.text());
            assert_eq!(0, txt.position());
        }

        #[test]
        fn test_at_non_edge() {
            let mut txt = new_with_position(
                String::from("abc "),
                1, // indicate `b`.
            );
            let new = new_with_position(
                String::from("abc "),
                2, // indicate `c`.
            );
            txt.forward();
            assert_eq!(new.text(), txt.text());
            assert_eq!(new.position(), txt.position());
        }

        #[test]
        fn test_at_tail() {
            let mut txt = new_with_position(
                String::from("abc "),
                3, // indicate tail.
            );
            txt.forward();
            assert_eq!(StyledGraphemes::from("abc "), txt.text());
            assert_eq!(3, txt.position());
        }

        #[test]
        fn test_at_head() {
            let mut txt = new_with_position(
                String::from("abc "),
                0, // indicate `a`.
            );
            let new = new_with_position(
                String::from("abc "),
                1, // indicate `b`.
            );
            txt.forward();
            assert_eq!(new.text(), txt.text());
            assert_eq!(new.position(), txt.position());
        }
    }

    mod to_head {
        use super::*;

        #[test]
        fn test_for_empty() {
            let mut txt = TextEditor::default();
            txt.move_to_head();
            assert_eq!(StyledGraphemes::from(" "), txt.text());
            assert_eq!(0, txt.position());
        }

        #[test]
        fn test_at_non_edge() {
            let mut txt = new_with_position(
                String::from("abc "),
                1, // indicate `b`.
            );
            let new = new_with_position(
                String::from("abc "),
                0, // indicate `a`.
            );
            txt.move_to_head();
            assert_eq!(new.text(), txt.text());
            assert_eq!(new.position(), txt.position());
        }

        #[test]
        fn test_at_tail() {
            let mut txt = new_with_position(
                String::from("abc "),
                3, // indicate tail.
            );
            let new = new_with_position(
                String::from("abc "),
                0, // indicate `a`.
            );
            txt.move_to_head();
            assert_eq!(new.text(), txt.text());
            assert_eq!(new.position(), txt.position());
        }

        #[test]
        fn test_at_head() {
            let mut txt = new_with_position(
                String::from("abc "),
                0, // indicate `a`.
            );
            txt.move_to_head();
            assert_eq!(StyledGraphemes::from("abc "), txt.text());
            assert_eq!(0, txt.position());
        }
    }

    mod to_tail {
        use super::*;

        #[test]
        fn test_for_empty() {
            let mut txt = TextEditor::default();
            txt.move_to_tail();
            assert_eq!(StyledGraphemes::from(" "), txt.text());
            assert_eq!(0, txt.position());
        }

        #[test]
        fn test_at_non_edge() {
            let mut txt = new_with_position(
                String::from("abc "),
                1, // indicate `b`.
            );
            let new = new_with_position(
                String::from("abc "),
                3, // indicate tail.
            );
            txt.move_to_tail();
            assert_eq!(new.text(), txt.text());
            assert_eq!(new.position(), txt.position());
        }

        #[test]
        fn test_at_tail() {
            let mut txt = new_with_position(
                String::from("abc "),
                3, // indicate tail.
            );
            txt.move_to_tail();
            assert_eq!(StyledGraphemes::from("abc "), txt.text());
            assert_eq!(3, txt.position());
        }

        #[test]
        fn test_at_head() {
            let mut txt = new_with_position(
                String::from("abc "),
                0, // indicate `a`.
            );
            let new = new_with_position(
                String::from("abc "),
                3, // indicate tail.
            );
            txt.move_to_tail();
            assert_eq!(new.text(), txt.text());
            assert_eq!(new.position(), txt.position());
        }
    }
}