Skip to main content

tui/widgets/
amount.rs

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
6use super::editor::Editor;
7
8/// A text field for amount text.
9#[derive(Debug, Clone, Default)]
10pub struct AmountWidget {
11    editor: Editor,
12}
13
14impl AmountWidget {
15    #[must_use]
16    pub fn with_value(value: impl Into<String>) -> Self {
17        Self {
18            editor: Editor::with_buffer(value),
19        }
20    }
21
22    /// Buffer text (the current amount string).
23    #[must_use]
24    pub fn value(&self) -> &str {
25        self.editor.buffer()
26    }
27
28    #[must_use]
29    pub fn editor(&self) -> &Editor {
30        &self.editor
31    }
32
33    pub fn insert_char(&mut self, c: char) {
34        self.editor.insert_char(c);
35    }
36
37    /// Direct access to the inner editor for motion and delete operations.
38    #[must_use]
39    pub fn as_editor_mut(&mut self) -> &mut Editor {
40        &mut self.editor
41    }
42}
43
44#[cfg(test)]
45mod tests {
46    use super::*;
47
48    #[test]
49    fn accepts_digits_and_separators() {
50        let mut w = AmountWidget::default();
51        for c in "100.5/3".chars() {
52            w.insert_char(c);
53        }
54        assert_eq!(w.value(), "100.5/3");
55    }
56
57    #[test]
58    fn accepts_negative_sign() {
59        let mut w = AmountWidget::default();
60        w.insert_char('-');
61        w.insert_char('5');
62        assert_eq!(w.value(), "-5");
63    }
64
65    #[test]
66    fn keeps_every_typed_character() {
67        let mut w = AmountWidget::default();
68        for c in "12,50 a".chars() {
69            w.insert_char(c);
70        }
71        assert_eq!(w.value(), "12,50 a");
72    }
73
74    #[test]
75    fn delete_backward_via_editor_mut() {
76        let mut w = AmountWidget::default();
77        w.insert_char('5');
78        w.insert_char('0');
79        w.as_editor_mut().delete_backward();
80        assert_eq!(w.value(), "5");
81    }
82
83    #[test]
84    fn with_value_sets_initial_buffer() {
85        let w = AmountWidget::with_value("42/7");
86        assert_eq!(w.value(), "42/7");
87    }
88}