bubbletea-widgets 0.1.12

A collection of reusable TUI components for building terminal applications with bubbletea-rs
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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
//! Tests for the textinput component.

use super::*;

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

    #[test]
    fn test_new_default_values() {
        // Test Go's: New()
        let input = new();

        assert_eq!(input.prompt, "> ");
        assert_eq!(input.placeholder, "");
        assert_eq!(input.echo_character, '*');
        assert_eq!(input.char_limit, 0);
        assert_eq!(input.width, 0);
        assert_eq!(input.value(), "");
        assert_eq!(input.position(), 0);
        assert!(!input.focused());
        assert_eq!(input.echo_mode, EchoMode::EchoNormal);
        assert!(input.err.is_none());
    }

    #[test]
    fn test_deprecated_new_model() {
        // Test Go's deprecated: NewModel
        #[allow(deprecated)]
        let input = new_model();
        assert_eq!(input.prompt, "> ");
        assert_eq!(input.value(), "");
    }

    #[test]
    fn test_set_value() {
        // Test Go's: SetValue(s string)
        let mut input = new();
        input.set_value("hello world");

        assert_eq!(input.value(), "hello world");
        assert_eq!(input.position(), input.value().len());
    }

    #[test]
    fn test_set_value_with_char_limit() {
        // Test character limit enforcement
        let mut input = new();
        input.set_char_limit(5);
        input.set_value("hello world"); // Should be truncated

        assert_eq!(input.value(), "hello");
        assert_eq!(input.value().len(), 5);
    }

    #[test]
    fn test_position() {
        // Test Go's: Position() int
        let mut input = new();
        input.set_value("test");

        assert_eq!(input.position(), 4); // Cursor at end

        input.set_cursor(2);
        assert_eq!(input.position(), 2);
    }

    #[test]
    fn test_set_cursor() {
        // Test Go's: SetCursor(pos int)
        let mut input = new();
        input.set_value("hello");

        input.set_cursor(2);
        assert_eq!(input.position(), 2);

        // Test bounds checking
        input.set_cursor(100); // Beyond end
        assert_eq!(input.position(), 5); // Should be clamped to end

        input.set_cursor(0);
        assert_eq!(input.position(), 0);
    }

    #[test]
    fn test_cursor_start_end() {
        // Test Go's: CursorStart() and CursorEnd()
        let mut input = new();
        input.set_value("hello world");
        input.set_cursor(5);

        input.cursor_start();
        assert_eq!(input.position(), 0);

        input.cursor_end();
        assert_eq!(input.position(), 11);
    }

    #[test]
    fn test_focused() {
        // Test Go's: Focused() bool, Focus() tea.Cmd, Blur()
        let mut input = new();

        assert!(!input.focused());

        std::mem::drop(input.focus());
        assert!(input.focused());

        input.blur();
        assert!(!input.focused());
    }

    #[test]
    fn test_reset() {
        // Test Go's: Reset()
        let mut input = new();
        input.set_value("some text");
        input.set_cursor(5);

        input.reset();

        assert_eq!(input.value(), "");
        assert_eq!(input.position(), 0);
    }

    #[test]
    fn test_echo_modes() {
        let mut input = new();
        input.set_value("secret");

        // Test EchoNormal
        input.set_echo_mode(EchoMode::EchoNormal);
        let view_normal = input.view();
        assert!(view_normal.contains("secret"));

        // Test EchoPassword
        input.set_echo_mode(EchoMode::EchoPassword);
        let view_password = input.view();
        assert!(view_password.contains("******")); // Should show asterisks
        assert!(!view_password.contains("secret")); // Should not show actual text

        // Test EchoNone
        input.set_echo_mode(EchoMode::EchoNone);
        let view_none = input.view();
        assert!(!view_none.contains("secret"));
        assert!(!view_none.contains("*"));
    }

    #[test]
    fn test_placeholder() {
        // Test placeholder functionality
        let mut input = new();
        input.set_placeholder("Enter text...");

        // With empty value, should show placeholder (remainder after cursor)
        let view_empty = input.view();
        // The current implementation shows cursor + remainder, so we check for remainder
        assert!(
            view_empty.contains("nter text"),
            "Should contain placeholder remainder"
        );

        // With value, should not show placeholder
        input.set_value("actual text");
        let view_with_text = input.view();
        assert!(!view_with_text.contains("Enter text"));
        assert!(!view_with_text.contains("nter text"));
        assert!(view_with_text.contains("actual"));
    }

    #[test]
    fn test_width_setting() {
        // Test width setting
        let mut input = new();
        input.set_width(50);

        assert_eq!(input.width, 50);
    }

    #[test]
    fn test_char_limit() {
        // Test character limit functionality
        let mut input = new();
        input.set_char_limit(10);

        assert_eq!(input.char_limit, 10);

        // Should enforce limit on set_value
        input.set_value("this is a very long string");
        assert!(input.value().len() <= 10);
    }

    #[test]
    fn test_suggestions() {
        // Test Go's: SetSuggestions, AvailableSuggestions, MatchedSuggestions, etc.
        let mut input = new();
        let suggestions = vec![
            "apple".to_string(),
            "application".to_string(),
            "banana".to_string(),
            "cherry".to_string(),
        ];

        input.set_suggestions(suggestions.clone());

        assert_eq!(input.available_suggestions(), suggestions);

        // Test matching
        input.set_value("app");
        input.update_suggestions();

        let matched = input.matched_suggestions();
        assert_eq!(matched.len(), 2);
        assert!(matched.contains(&"apple".to_string()));
        assert!(matched.contains(&"application".to_string()));
        assert!(!matched.contains(&"banana".to_string()));
    }

    #[test]
    fn test_current_suggestion() {
        // Test Go's: CurrentSuggestion, CurrentSuggestionIndex
        let mut input = new();
        input.set_suggestions(vec!["apple".to_string(), "application".to_string()]);
        input.set_value("app");
        input.update_suggestions();

        assert_eq!(input.current_suggestion_index(), 0);
        assert_eq!(input.current_suggestion(), "apple");

        input.next_suggestion();
        assert_eq!(input.current_suggestion_index(), 1);
        assert_eq!(input.current_suggestion(), "application");

        input.previous_suggestion();
        assert_eq!(input.current_suggestion_index(), 0);
        assert_eq!(input.current_suggestion(), "apple");
    }

    #[test]
    fn test_default_trait_implementation() {
        // Test Default trait implementation
        let input = Model::default();
        assert_eq!(input.value(), "");
        assert_eq!(input.prompt, "> ");
        assert!(!input.focused());
    }

    // Tests matching Go's textinput_test.go exactly

    #[test]
    fn test_current_suggestion_go_compat() {
        // Test Go's: Test_CurrentSuggestion
        let mut textinput = new();

        let suggestion = textinput.current_suggestion();
        let expected = "";
        assert_eq!(
            suggestion, expected,
            "Error: expected no current suggestion but was {}",
            suggestion
        );

        textinput.set_suggestions(vec![
            "test1".to_string(),
            "test2".to_string(),
            "test3".to_string(),
        ]);
        let suggestion = textinput.current_suggestion();
        let expected = "";
        assert_eq!(
            suggestion, expected,
            "Error: expected no current suggestion but was {}",
            suggestion
        );

        textinput.set_value("test");
        textinput.update_suggestions();
        textinput.next_suggestion();
        let suggestion = textinput.current_suggestion();
        let expected = "test2";
        assert_eq!(
            suggestion, expected,
            "Error: expected first suggestion but was {}",
            suggestion
        );

        textinput.blur();
        let view = textinput.view();
        assert!(!view.ends_with("test2"), "Error: suggestions should not be rendered when input isn't focused. expected \"> test\" but got \"{}\"", view);
    }

    #[test]
    fn test_slicing_outside_cap() {
        // Test Go's: Test_SlicingOutsideCap
        let mut textinput = new();
        textinput.set_placeholder("作業ディレクトリを指定してください"); // Japanese text
        textinput.set_width(32);

        // Should not panic when rendering with Unicode characters and width constraints
        let _view = textinput.view();
        // Test passes if no panic occurs
    }

    #[test]
    fn test_validate_func_credit_card_example() {
        // Test Go's: ExampleValidateFunc (converted to test)
        let mut credit_card_number = new();
        credit_card_number.set_placeholder("4505 **** **** 1234");
        std::mem::drop(credit_card_number.focus());
        credit_card_number.set_char_limit(20);
        credit_card_number.set_width(30);
        credit_card_number.prompt = "".to_string();

        // Credit card validation function matching grouped format: XXXX XXXX XXXX XXXX
        let credit_card_validator: ValidateFunc = Box::new(|s: &str| {
            // Max length: 19 (16 digits + 3 spaces)
            if s.len() > 19 {
                return Err("CCN is too long".to_string());
            }

            let chars: Vec<char> = s.chars().collect();
            for (i, ch) in chars.iter().enumerate() {
                // Require spaces at positions 4, 9, and 14 if those positions exist
                if i == 4 || i == 9 || i == 14 {
                    if *ch != ' ' {
                        return Err("CCN must separate groups with spaces".to_string());
                    }
                } else if !ch.is_ascii_digit() {
                    return Err("Invalid number format".to_string());
                }
            }

            Ok(())
        });

        credit_card_number.set_validate(credit_card_validator);

        // Test valid credit card format
        credit_card_number.set_value("4505 1234 5678 1234");
        assert!(
            credit_card_number.err.is_none(),
            "Valid credit card should not have error"
        );

        // Test invalid - too long
        credit_card_number.set_value("4505 1234 5678 1234 5678");
        assert!(credit_card_number.err.is_some());
        assert!(credit_card_number
            .err
            .as_ref()
            .unwrap()
            .contains("too long"));

        // Test invalid - missing space
        credit_card_number.set_value("45051234");
        assert!(credit_card_number.err.is_some());
        assert!(credit_card_number
            .err
            .as_ref()
            .unwrap()
            .contains("separate groups"));

        // Test invalid - non-numeric
        credit_card_number.set_value("450a 1234 5678 1234");
        assert!(credit_card_number.err.is_some());
    }

    #[test]
    fn test_component_trait_implementation() {
        // Test Component trait implementation
        use crate::Component;

        let mut input = new();

        // Test initial state
        assert!(
            !Component::focused(&input),
            "Input should not be focused initially"
        );

        // Test focus method returns Some(Cmd)
        let focus_cmd = Component::focus(&mut input);
        assert!(
            focus_cmd.is_some(),
            "Component::focus should return Some(Cmd)"
        );
        assert!(
            Component::focused(&input),
            "Input should be focused after Component::focus() call"
        );

        // Test blur method
        Component::blur(&mut input);
        assert!(
            !Component::focused(&input),
            "Input should not be focused after Component::blur() call"
        );

        // Test focus/blur cycle using Component trait methods
        for _ in 0..3 {
            let _ = Component::focus(&mut input);
            assert!(
                Component::focused(&input),
                "Input should be focused after Component::focus()"
            );
            Component::blur(&mut input);
            assert!(
                !Component::focused(&input),
                "Input should not be focused after Component::blur()"
            );
        }

        // Test that Component trait methods work alongside regular methods
        std::mem::drop(input.focus()); // Regular focus method
        assert!(
            Component::focused(&input),
            "Component::focused should work with regular focus"
        );
        Component::blur(&mut input); // Component blur method
        assert!(
            !input.focused(),
            "Regular focused() should work with Component::blur"
        );
    }

    /// Tests specifically for placeholder rendering bug fix and regression prevention
    mod placeholder_rendering_tests {
        use super::*;

        #[test]
        fn test_placeholder_no_duplication_basic() {
            // Test core fix: placeholder should not duplicate first character
            let mut input = new();
            input.set_placeholder("Nickname");
            std::mem::drop(input.focus()); // Focus to show cursor on first char

            let view = input.view();

            // Should show: "> " + cursor with 'N' + remaining "ickname"
            // NOT: "> " + cursor with 'N' + full "Nickname"
            assert!(view.starts_with("> "), "Should start with prompt");

            // Count occurrences of 'N' - should be exactly 1 (in cursor position)
            let n_count = view.chars().filter(|&c| c == 'N').count();
            assert_eq!(
                n_count, 1,
                "Should have exactly one 'N' character, found {} in: '{}'",
                n_count, view
            );

            // Should contain the remaining part of placeholder
            assert!(
                view.contains("ickname"),
                "Should contain remaining placeholder 'ickname' in: '{}'",
                view
            );
        }

        #[test]
        fn test_placeholder_specific_examples() {
            // Test the specific examples from the original bug report
            let test_cases = [
                ("Nickname", "ickname"),
                ("Email", "mail"),
                ("Password", "assword"),
            ];

            for (placeholder, expected_remainder) in test_cases {
                let mut input = new();
                input.set_placeholder(placeholder);
                std::mem::drop(input.focus());

                let view = input.view();

                // Should start with prompt
                assert!(
                    view.starts_with("> "),
                    "Placeholder '{}' should start with prompt",
                    placeholder
                );

                // Should contain remaining part after first character
                assert!(
                    view.contains(expected_remainder),
                    "Placeholder '{}' should contain remainder '{}' but view is: '{}'",
                    placeholder,
                    expected_remainder,
                    view
                );

                // Should NOT contain the full placeholder string duplicated
                let first_char = placeholder.chars().next().unwrap();
                let full_placeholder_occurrences = view.matches(placeholder).count();
                assert_eq!(
                    full_placeholder_occurrences, 0,
                    "Placeholder '{}' should not appear in full in view: '{}'",
                    placeholder, view
                );

                // First character should appear exactly once (in cursor)
                let first_char_count = view.chars().filter(|&c| c == first_char).count();
                assert_eq!(
                    first_char_count, 1,
                    "First character '{}' should appear exactly once, found {} in: '{}'",
                    first_char, first_char_count, view
                );
            }
        }

        #[test]
        fn test_placeholder_with_different_cursor_modes() {
            use crate::cursor::Mode;

            let mut input = new();
            input.set_placeholder("Test");
            std::mem::drop(input.focus());

            // Test with different cursor modes
            let modes = [Mode::Blink, Mode::Static, Mode::Hide];

            for mode in modes {
                let _ = input.cursor.set_mode(mode);
                let view = input.view();

                // Regardless of cursor mode, should not duplicate
                let t_count = view.chars().filter(|&c| c == 'T').count();
                assert!(
                    t_count <= 1,
                    "With cursor mode {:?}, should have at most one 'T', found {} in: '{}'",
                    mode,
                    t_count,
                    view
                );

                // Should contain remainder
                assert!(
                    view.contains("est") || mode == Mode::Hide,
                    "With cursor mode {:?}, should contain 'est' or be hidden, view: '{}'",
                    mode,
                    view
                );
            }
        }

        #[test]
        fn test_placeholder_blurred_vs_focused() {
            let mut input = new();
            input.set_placeholder("Example");

            // When blurred, should show placeholder content (cursor + remainder)
            input.blur();
            let blurred_view = input.view();

            // The placeholder_view always shows cursor + remainder regardless of focus state
            assert!(
                blurred_view.contains("xample"),
                "Blurred view should show placeholder content: '{}'",
                blurred_view
            );

            // When focused, should show cursor + remainder only
            std::mem::drop(input.focus());
            let focused_view = input.view();

            // Should NOT show full "Example" duplicated
            let example_count = focused_view.matches("Example").count();
            assert_eq!(
                example_count, 0,
                "Focused view should not contain full 'Example': '{}'",
                focused_view
            );

            // Should show remainder
            assert!(
                focused_view.contains("xample"),
                "Focused view should contain 'xample': '{}'",
                focused_view
            );
        }

        #[test]
        fn test_placeholder_edge_cases() {
            // Single character placeholder
            let mut input = new();
            input.set_placeholder("A");
            std::mem::drop(input.focus());
            let view = input.view();

            let a_count = view.chars().filter(|&c| c == 'A').count();
            assert_eq!(
                a_count, 1,
                "Single char placeholder should have exactly one 'A': '{}'",
                view
            );

            // Empty placeholder
            let mut input2 = new();
            input2.set_placeholder("");
            std::mem::drop(input2.focus());
            let view2 = input2.view();
            // Should not panic and should show just prompt + cursor space
            assert!(
                view2.starts_with("> "),
                "Empty placeholder should show prompt"
            );

            // Unicode placeholder
            let mut input3 = new();
            input3.set_placeholder("测试"); // Chinese characters
            std::mem::drop(input3.focus());
            let view3 = input3.view();

            // Should handle Unicode correctly without duplication
            let first_char_count = view3.chars().filter(|&c| c == '').count();
            assert!(
                first_char_count <= 1,
                "Unicode placeholder should not duplicate first char: '{}'",
                view3
            );
        }

        #[test]
        fn test_placeholder_transitions() {
            let mut input = new();
            input.set_placeholder("Username");
            std::mem::drop(input.focus());

            // Focused empty input - should show cursor + remainder
            let empty_focused = input.view();
            assert!(
                empty_focused.contains("sername"),
                "Should show remainder when focused and empty"
            );

            // Add some text - placeholder should disappear
            input.set_value("user");
            let with_text = input.view();
            assert!(with_text.contains("user"), "Should show actual text");
            assert!(
                !with_text.contains("Username"),
                "Should not show placeholder when text present"
            );
            assert!(
                !with_text.contains("sername"),
                "Should not show placeholder remainder when text present"
            );

            // Clear text - placeholder should return
            input.set_value("");
            let cleared = input.view();
            assert!(
                cleared.contains("sername"),
                "Should show remainder again when cleared"
            );
        }

        #[test]
        fn test_placeholder_with_width_constraints() {
            let mut input = new();
            input.set_placeholder("VeryLongPlaceholderText");
            input.set_width(10);
            std::mem::drop(input.focus());

            let view = input.view();

            // Should not duplicate first character even with width constraints
            let v_count = view.chars().filter(|&c| c == 'V').count();
            assert_eq!(
                v_count, 1,
                "Should have exactly one 'V' even with width constraints: '{}'",
                view
            );

            // Should handle width properly
            assert!(view.len() >= 10, "Should respect minimum width");
        }

        #[test]
        fn test_regression_original_bug_would_fail() {
            // This test would fail with the original bug (p[0..] instead of p[1..])
            let mut input = new();
            input.set_placeholder("Bug");
            std::mem::drop(input.focus());

            let view = input.view();

            // The original bug would produce "> B" + "Bug" = "> BBug"
            // The fix should produce "> B" + "ug" = "> Bug"
            assert!(
                !view.contains("BBug"),
                "Should not show duplicated 'BBug' - this indicates the original bug: '{}'",
                view
            );

            // Should show correct format
            let b_count = view.chars().filter(|&c| c == 'B').count();
            assert_eq!(b_count, 1, "Should have exactly one 'B': '{}'", view);
            assert!(
                view.contains("ug"),
                "Should contain remainder 'ug': '{}'",
                view
            );
        }

        #[test]
        fn test_placeholder_styling_preserved() {
            use lipgloss_extras::prelude::*;

            let mut input = new();
            input.set_placeholder("Styled");

            // Set custom placeholder style
            input.placeholder_style = Style::new().foreground(Color::from("blue"));
            std::mem::drop(input.focus());

            let view = input.view();

            // Should not duplicate regardless of styling
            let s_count = view.chars().filter(|&c| c == 'S').count();
            assert_eq!(
                s_count, 1,
                "Styled placeholder should not duplicate: '{}'",
                view
            );

            // Should contain remainder
            assert!(
                view.contains("tyled"),
                "Should contain styled remainder: '{}'",
                view
            );
        }
    }
}