revue 2.71.1

A Vue-style TUI framework for Rust with CSS styling
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
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
//! Masked input widget for passwords and sensitive data
//!
//! Provides input fields that hide or mask the entered text, perfect for
//! passwords, PINs, credit card numbers, and other sensitive information.

#![allow(clippy::iter_skip_next)]
//!
//! # Example
//!
//! ```rust,ignore
//! use revue::widget::{MaskedInput, MaskStyle, masked_input, password_input};
//!
//! // Password input (dots)
//! let password = MaskedInput::password()
//!     .placeholder("Enter password");
//!
//! // PIN input (asterisks)
//! let pin = MaskedInput::new()
//!     .mask_char('*')
//!     .max_length(4);
//!
//! // Credit card input (show last 4)
//! let card = MaskedInput::new()
//!     .mask_style(MaskStyle::ShowLast(4))
//!     .placeholder("Card number");
//!
//! // Using helper
//! let pwd = password_input("Password");
//! ```

use crate::style::Color;
use crate::utils::display_width;
use crate::widget::theme::{DARK_GRAY, DISABLED_FG, PLACEHOLDER_FG};
use crate::widget::{RenderContext, View, WidgetProps};
use crate::{impl_props_builders, impl_styled_view};

/// Default peek timeout in frames for MaskStyle::Peek
///
/// This controls how long the last typed character remains visible
/// before being masked. At 60 FPS, 10 frames ≈ 167ms.
const DEFAULT_PEEK_TIMEOUT: usize = 10;

/// Mask display style
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum MaskStyle {
    /// Show all characters as mask (default)
    #[default]
    Full,
    /// Show last N characters
    ShowLast(usize),
    /// Show first N characters
    ShowFirst(usize),
    /// Show characters briefly then mask
    Peek,
    /// Show nothing (empty)
    Hidden,
}

/// Input validation result
#[derive(Clone, Debug, PartialEq)]
pub enum ValidationState {
    /// No validation performed
    None,
    /// Input is valid
    Valid,
    /// Input is invalid with message
    Invalid(String),
    /// Validation in progress
    Validating,
}

/// Masked input widget
#[derive(Clone, Debug)]
pub struct MaskedInput {
    /// Current value
    value: String,
    /// Mask character
    mask_char: char,
    /// Mask style
    mask_style: MaskStyle,
    /// Placeholder text
    placeholder: Option<String>,
    /// Label text
    label: Option<String>,
    /// Maximum length (0 = unlimited)
    max_length: usize,
    /// Minimum length for validation
    min_length: usize,
    /// Cursor position
    cursor: usize,
    /// Whether input is focused
    focused: bool,
    /// Whether input is disabled
    disabled: bool,
    /// Foreground color
    fg: Option<Color>,
    /// Background color
    bg: Option<Color>,
    /// Width of input field
    width: Option<u16>,
    /// Validation state
    validation: ValidationState,
    /// Show strength indicator (for passwords)
    show_strength: bool,
    /// Allow reveal toggle
    allow_reveal: bool,
    /// Currently revealing
    revealing: bool,
    /// Peek timeout (frames)
    peek_timeout: usize,
    /// Current peek countdown
    peek_countdown: usize,
    /// CSS styling properties (id, classes)
    props: WidgetProps,
}

impl MaskedInput {
    /// Create new masked input
    pub fn new() -> Self {
        Self {
            value: String::new(),
            mask_char: '',
            mask_style: MaskStyle::Full,
            placeholder: None,
            label: None,
            max_length: 0,
            min_length: 0,
            cursor: 0,
            focused: false,
            disabled: false,
            fg: None,
            bg: None,
            width: None,
            validation: ValidationState::None,
            show_strength: false,
            allow_reveal: false,
            revealing: false,
            peek_timeout: DEFAULT_PEEK_TIMEOUT,
            peek_countdown: 0,
            props: WidgetProps::new(),
        }
    }

    /// Create password input with defaults
    pub fn password() -> Self {
        Self::new()
            .mask_char('')
            .mask_style(MaskStyle::Full)
            .show_strength(true)
    }

    /// Create PIN input
    pub fn pin(length: usize) -> Self {
        Self::new()
            .mask_char('*')
            .max_length(length)
            .mask_style(MaskStyle::Full)
    }

    /// Create credit card input
    pub fn credit_card() -> Self {
        Self::new()
            .mask_char('')
            .mask_style(MaskStyle::ShowLast(4))
            .max_length(16)
    }

    /// Set mask character
    pub fn mask_char(mut self, c: char) -> Self {
        self.mask_char = c;
        self
    }

    /// Set mask style
    pub fn mask_style(mut self, style: MaskStyle) -> Self {
        self.mask_style = style;
        self
    }

    /// Set placeholder text
    pub fn placeholder(mut self, text: impl Into<String>) -> Self {
        self.placeholder = Some(text.into());
        self
    }

    /// Set label
    pub fn label(mut self, text: impl Into<String>) -> Self {
        self.label = Some(text.into());
        self
    }

    /// Set maximum length
    pub fn max_length(mut self, len: usize) -> Self {
        self.max_length = len;
        self
    }

    /// Set minimum length
    pub fn min_length(mut self, len: usize) -> Self {
        self.min_length = len;
        self
    }

    /// Set focused state
    pub fn focused(mut self, focused: bool) -> Self {
        self.focused = focused;
        self
    }

    /// Set disabled state
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    /// Set foreground color
    pub fn fg(mut self, color: Color) -> Self {
        self.fg = Some(color);
        self
    }

    /// Set background color
    pub fn bg(mut self, color: Color) -> Self {
        self.bg = Some(color);
        self
    }

    /// Set width
    pub fn width(mut self, width: u16) -> Self {
        self.width = Some(width);
        self
    }

    /// Show password strength indicator
    pub fn show_strength(mut self, show: bool) -> Self {
        self.show_strength = show;
        self
    }

    /// Allow reveal toggle
    pub fn allow_reveal(mut self, allow: bool) -> Self {
        self.allow_reveal = allow;
        self
    }

    /// Set initial value
    pub fn value(mut self, value: impl Into<String>) -> Self {
        self.value = value.into();
        self.cursor = self.value.len();
        self
    }

    /// Get current value
    pub fn get_value(&self) -> &str {
        &self.value
    }

    /// Get mask character
    pub fn get_mask_char(&self) -> char {
        self.mask_char
    }

    /// Get mask style
    pub fn get_mask_style(&self) -> MaskStyle {
        self.mask_style
    }

    /// Get placeholder text
    pub fn get_placeholder(&self) -> Option<&String> {
        self.placeholder.as_ref()
    }

    /// Get label text
    pub fn get_label(&self) -> Option<&String> {
        self.label.as_ref()
    }

    /// Get maximum length
    pub fn get_max_length(&self) -> usize {
        self.max_length
    }

    /// Get minimum length
    pub fn get_min_length(&self) -> usize {
        self.min_length
    }

    /// Get cursor position
    pub fn get_cursor(&self) -> usize {
        self.cursor
    }

    /// Set cursor position
    pub fn set_cursor(&mut self, pos: usize) {
        self.cursor = pos.min(self.value.len());
    }

    /// Get focused state
    pub fn get_focused(&self) -> bool {
        self.focused
    }

    /// Get disabled state
    pub fn get_disabled(&self) -> bool {
        self.disabled
    }

    /// Get foreground color
    pub fn get_fg(&self) -> Option<Color> {
        self.fg
    }

    /// Get background color
    pub fn get_bg(&self) -> Option<Color> {
        self.bg
    }

    /// Get width
    pub fn get_width(&self) -> Option<u16> {
        self.width
    }

    /// Get show strength indicator state
    pub fn get_show_strength(&self) -> bool {
        self.show_strength
    }

    /// Get allow reveal state
    pub fn get_allow_reveal(&self) -> bool {
        self.allow_reveal
    }

    /// Get revealing state
    pub fn get_revealing(&self) -> bool {
        self.revealing
    }

    /// Set revealing state
    pub fn set_revealing(&mut self, revealing: bool) {
        self.revealing = revealing;
    }

    /// Get peek countdown
    pub fn get_peek_countdown(&self) -> usize {
        self.peek_countdown
    }

    /// Set peek countdown
    pub fn set_peek_countdown(&mut self, countdown: usize) {
        self.peek_countdown = countdown;
    }

    /// Get validation state
    pub fn get_validation(&self) -> &ValidationState {
        &self.validation
    }

    /// Set value programmatically
    pub fn set_value(&mut self, value: impl Into<String>) {
        self.value = value.into();
        self.cursor = self.cursor.min(self.value.len());
    }

    /// Clear the input
    pub fn clear(&mut self) {
        self.value.clear();
        self.cursor = 0;
    }

    /// Toggle reveal mode
    pub fn toggle_reveal(&mut self) {
        if self.allow_reveal {
            self.revealing = !self.revealing;
        }
    }

    /// Insert character at cursor
    pub fn insert_char(&mut self, c: char) {
        if self.disabled {
            return;
        }

        // Check max length
        if self.max_length > 0 && self.value.len() >= self.max_length {
            return;
        }

        self.value.insert(self.cursor, c);
        self.cursor += 1;

        // Start peek countdown
        if matches!(self.mask_style, MaskStyle::Peek) {
            self.peek_countdown = self.peek_timeout;
        }
    }

    /// Delete character before cursor
    pub fn delete_backward(&mut self) {
        if self.disabled || self.cursor == 0 {
            return;
        }

        self.cursor -= 1;
        self.value.remove(self.cursor);
    }

    /// Delete character at cursor
    pub fn delete_forward(&mut self) {
        if self.disabled || self.cursor >= self.value.len() {
            return;
        }

        self.value.remove(self.cursor);
    }

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

    /// Move cursor right
    pub fn move_right(&mut self) {
        if self.cursor < self.value.len() {
            self.cursor += 1;
        }
    }

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

    /// Move cursor to end
    pub fn move_end(&mut self) {
        self.cursor = self.value.len();
    }

    /// Update (call each frame for peek mode)
    pub fn update(&mut self) {
        if self.peek_countdown > 0 {
            self.peek_countdown -= 1;
        }
    }

    /// Calculate password strength (0-4)
    pub fn password_strength(&self) -> usize {
        let len = self.value.len();
        let has_lower = self.value.chars().any(|c| c.is_lowercase());
        let has_upper = self.value.chars().any(|c| c.is_uppercase());
        let has_digit = self.value.chars().any(|c| c.is_ascii_digit());
        let has_special = self.value.chars().any(|c| !c.is_alphanumeric());

        let mut strength = 0;

        if len >= 8 {
            strength += 1;
        }
        if len >= 12 {
            strength += 1;
        }
        if has_lower && has_upper {
            strength += 1;
        }
        if has_digit {
            strength += 1;
        }
        if has_special {
            strength += 1;
        }

        strength.min(4)
    }

    /// Get strength label
    pub fn strength_label(&self) -> &str {
        match self.password_strength() {
            0 => "Very Weak",
            1 => "Weak",
            2 => "Fair",
            3 => "Strong",
            _ => "Very Strong",
        }
    }

    /// Get strength color
    pub fn strength_color(&self) -> Color {
        match self.password_strength() {
            0 => Color::RED,
            1 => Color::rgb(255, 128, 0), // Orange
            2 => Color::YELLOW,
            3 => Color::rgb(128, 255, 0), // Light green
            _ => Color::GREEN,
        }
    }

    /// Validate the input
    pub fn validate(&mut self) -> bool {
        if self.min_length > 0 && self.value.len() < self.min_length {
            self.validation = ValidationState::Invalid(format!(
                "Minimum {} characters required",
                self.min_length
            ));
            return false;
        }

        self.validation = ValidationState::Valid;
        true
    }

    /// Get masked display string
    ///
    /// This method is optimized to minimize string allocations by:
    /// - Pre-allocating strings with known capacity
    /// - Avoiding repeated `.to_string().repeat()` calls
    /// - Using `extend` with char iterators instead of format!
    pub fn masked_display(&self) -> String {
        if self.revealing {
            return self.value.clone();
        }

        let len = self.value.len();
        if len == 0 {
            return String::new();
        }

        match self.mask_style {
            MaskStyle::Full => {
                // Pre-allocate with exact capacity
                std::iter::repeat_n(self.mask_char, len).collect()
            }
            MaskStyle::ShowLast(n) => {
                if len <= n {
                    self.value.clone()
                } else {
                    let mask_count = len - n;
                    let mut result = String::with_capacity(len);
                    result.extend(std::iter::repeat_n(self.mask_char, mask_count));
                    result.push_str(&self.value[len - n..]);
                    result
                }
            }
            MaskStyle::ShowFirst(n) => {
                if len <= n {
                    self.value.clone()
                } else {
                    let mut result = String::with_capacity(len);
                    result.push_str(&self.value[..n]);
                    result.extend(std::iter::repeat_n(self.mask_char, len - n));
                    result
                }
            }
            MaskStyle::Peek => {
                if self.peek_countdown > 0 && self.cursor > 0 && self.cursor <= len {
                    // Show the last typed character
                    // Use char_indices for O(n) instead of O(n²) with .chars().nth()
                    let last_char = self
                        .value
                        .char_indices()
                        .nth(self.cursor - 1)
                        .map(|(_, c)| c)
                        .unwrap_or(' ');
                    let mut result = String::with_capacity(len);
                    result.extend(std::iter::repeat_n(self.mask_char, self.cursor - 1));
                    result.push(last_char);
                    result.extend(std::iter::repeat_n(self.mask_char, len - self.cursor));
                    result
                } else {
                    std::iter::repeat_n(self.mask_char, len).collect()
                }
            }
            MaskStyle::Hidden => String::new(),
        }
    }
}

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

impl View for MaskedInput {
    crate::impl_view_meta!("MaskedInput");

    fn render(&self, ctx: &mut RenderContext) {
        use crate::widget::stack::{hstack, vstack};
        use crate::widget::Text;

        let mut content = vstack();

        // Label
        if let Some(label) = &self.label {
            content = content.child(Text::new(label).bold());
        }

        // Input field
        let display = if self.value.is_empty() {
            self.placeholder.clone().unwrap_or_default()
        } else {
            self.masked_display()
        };

        let is_placeholder = self.value.is_empty() && self.placeholder.is_some();

        // Build input display with pre-allocated padding
        let width = self.width.unwrap_or(20) as usize;
        let display_w = display_width(&display);
        let padded = if display_w < width {
            let mut result = String::with_capacity(width);
            result.push_str(&display);
            result.extend(std::iter::repeat_n(' ', width - display_w));
            result
        } else {
            crate::utils::truncate_to_width(&display, width).to_owned()
        };

        // Insert cursor if focused
        let display_with_cursor = if self.focused && !self.disabled {
            let cursor_pos = self.cursor.min(padded.chars().count());
            // Use iterators for O(n) instead of O(n²) with .chars().nth()
            let before: String = padded.chars().take(cursor_pos).collect();
            let cursor_char = padded.chars().skip(cursor_pos).next().unwrap_or(' ');
            let after: String = padded.chars().skip(cursor_pos + 1).collect();
            (before, cursor_char, after)
        } else {
            (padded.clone(), ' ', String::new())
        };

        // Render input box
        let mut input_text = if self.focused && !self.disabled {
            hstack()
                .child(Text::new(display_with_cursor.0))
                .child(
                    Text::new(display_with_cursor.1.to_string())
                        .bg(Color::WHITE)
                        .fg(Color::BLACK),
                )
                .child(Text::new(display_with_cursor.2))
        } else {
            let mut text = Text::new(&padded);
            if is_placeholder {
                text = text.fg(PLACEHOLDER_FG);
            } else if self.disabled {
                text = text.fg(DISABLED_FG);
            } else if let Some(fg) = self.fg {
                text = text.fg(fg);
            }
            hstack().child(text)
        };

        // Add reveal indicator
        if self.allow_reveal {
            let eye = if self.revealing {
                "👁"
            } else {
                "👁‍🗨"
            };
            input_text = input_text.child(Text::new(format!(" {}", eye)));
        }

        // Wrap in border
        let border_color = if self.disabled {
            DARK_GRAY
        } else if matches!(self.validation, ValidationState::Invalid(_)) {
            Color::RED
        } else if matches!(self.validation, ValidationState::Valid) {
            Color::GREEN
        } else if self.focused {
            Color::CYAN
        } else {
            PLACEHOLDER_FG
        };

        let bordered = hstack()
            .child(Text::new("[").fg(border_color))
            .child(input_text)
            .child(Text::new("]").fg(border_color));

        content = content.child(bordered);

        // Password strength indicator
        if self.show_strength && !self.value.is_empty() {
            let strength = self.password_strength();
            let color = self.strength_color();
            // Pre-allocate strength bar (max 5 chars = strength + 1)
            let bar: String = std::iter::repeat_n('', strength + 1).collect();
            let empty: String = std::iter::repeat_n('', 4 - strength).collect();

            let strength_display = hstack()
                .child(Text::new(&bar).fg(color))
                .child(Text::new(&empty).fg(DARK_GRAY))
                .child(Text::new(format!(" {}", self.strength_label())).fg(color));

            content = content.child(strength_display);
        }

        // Validation message
        if let ValidationState::Invalid(msg) = &self.validation {
            content = content.child(Text::new(msg).fg(Color::RED));
        }

        content.render(ctx);
    }
}

impl_styled_view!(MaskedInput);
impl_props_builders!(MaskedInput);

impl MaskedInput {
    /// Set element ID for CSS selector (#id)
    pub fn set_id(&mut self, id: impl Into<String>) {
        self.props.id = Some(id.into());
    }

    /// Add a CSS class
    pub fn add_class(&mut self, class: impl Into<String>) {
        let class_str = class.into();
        if !self.props.classes.contains(&class_str) {
            self.props.classes.push(class_str);
        }
    }

    /// Remove a CSS class
    pub fn remove_class(&mut self, class: &str) {
        self.props.classes.retain(|c| c != class);
    }

    /// Toggle a CSS class
    pub fn toggle_class(&mut self, class: &str) {
        if self.has_class(class) {
            self.remove_class(class);
        } else {
            self.props.classes.push(class.to_string());
        }
    }

    /// Check if widget has a CSS class
    pub fn has_class(&self, class: &str) -> bool {
        self.props.classes.iter().any(|c| c == class)
    }

    /// Get the CSS classes as a slice
    pub fn get_classes(&self) -> &[String] {
        &self.props.classes
    }

    /// Get the element ID
    pub fn get_id(&self) -> Option<&str> {
        self.props.id.as_deref()
    }
}

/// Create a masked input
pub fn masked_input() -> MaskedInput {
    MaskedInput::new()
}

/// Create a password input
pub fn password_input(placeholder: impl Into<String>) -> MaskedInput {
    MaskedInput::password().placeholder(placeholder)
}

/// Create a PIN input
pub fn pin_input(length: usize) -> MaskedInput {
    MaskedInput::pin(length)
}

/// Create a credit card input
pub fn credit_card_input() -> MaskedInput {
    MaskedInput::credit_card()
}