1
//! Numeric amount entry widget.
2
//!
3
//! Wraps an [`Editor`] and keeps every typed character; the server refuses
4
//! text that is not an amount.
5

            
6
use super::editor::Editor;
7

            
8
/// A text field for amount text.
9
#[derive(Debug, Clone, Default)]
10
pub struct AmountWidget {
11
    editor: Editor,
12
}
13

            
14
impl AmountWidget {
15
    #[must_use]
16
289
    pub fn with_value(value: impl Into<String>) -> Self {
17
289
        Self {
18
289
            editor: Editor::with_buffer(value),
19
289
        }
20
289
    }
21

            
22
    /// Buffer text (the current amount string).
23
    #[must_use]
24
2567
    pub fn value(&self) -> &str {
25
2567
        self.editor.buffer()
26
2567
    }
27

            
28
    #[must_use]
29
444
    pub fn editor(&self) -> &Editor {
30
444
        &self.editor
31
444
    }
32

            
33
150
    pub fn insert_char(&mut self, c: char) {
34
150
        self.editor.insert_char(c);
35
150
    }
36

            
37
    /// Direct access to the inner editor for motion and delete operations.
38
    #[must_use]
39
49
    pub fn as_editor_mut(&mut self) -> &mut Editor {
40
49
        &mut self.editor
41
49
    }
42
}
43

            
44
#[cfg(test)]
45
mod tests {
46
    use super::*;
47

            
48
    #[test]
49
1
    fn accepts_digits_and_separators() {
50
1
        let mut w = AmountWidget::default();
51
1
        for c in "100.5/3".chars() {
52
7
            w.insert_char(c);
53
        }
54
1
        assert_eq!(w.value(), "100.5/3");
55
1
    }
56

            
57
    #[test]
58
1
    fn accepts_negative_sign() {
59
1
        let mut w = AmountWidget::default();
60
1
        w.insert_char('-');
61
1
        w.insert_char('5');
62
1
        assert_eq!(w.value(), "-5");
63
1
    }
64

            
65
    #[test]
66
1
    fn keeps_every_typed_character() {
67
1
        let mut w = AmountWidget::default();
68
1
        for c in "12,50 a".chars() {
69
7
            w.insert_char(c);
70
        }
71
1
        assert_eq!(w.value(), "12,50 a");
72
1
    }
73

            
74
    #[test]
75
1
    fn delete_backward_via_editor_mut() {
76
1
        let mut w = AmountWidget::default();
77
1
        w.insert_char('5');
78
1
        w.insert_char('0');
79
1
        w.as_editor_mut().delete_backward();
80
1
        assert_eq!(w.value(), "5");
81
1
    }
82

            
83
    #[test]
84
1
    fn with_value_sets_initial_buffer() {
85
1
        let w = AmountWidget::with_value("42/7");
86
1
        assert_eq!(w.value(), "42/7");
87
1
    }
88
}