1
//! Free-text date entry widget.
2
//!
3
//! Wraps an [`Editor`] for free-text date entry (`YYYY-MM-DDTHH:MM` / RFC3339).
4
//! New widgets are pre-seeded with the current instant (RFC3339). Up/Down day-stepping is
5
//! available via [`DateWidget::step`].
6

            
7
use forms::{now_instant, step_date};
8

            
9
use super::editor::Editor;
10

            
11
/// A text field for date entry.
12
#[derive(Debug, Clone)]
13
pub struct DateWidget {
14
    editor: Editor,
15
}
16

            
17
/// A date widget pre-seeded with the current instant (RFC3339).
18
impl Default for DateWidget {
19
633
    fn default() -> Self {
20
633
        Self {
21
633
            editor: Editor::with_buffer(now_instant()),
22
633
        }
23
633
    }
24
}
25

            
26
impl DateWidget {
27
    #[must_use]
28
360
    pub fn with_value(value: impl Into<String>) -> Self {
29
360
        Self {
30
360
            editor: Editor::with_buffer(value),
31
360
        }
32
360
    }
33

            
34
    /// Buffer text (the current date string).
35
    #[must_use]
36
1033
    pub fn value(&self) -> &str {
37
1033
        self.editor.buffer()
38
1033
    }
39

            
40
    #[must_use]
41
276
    pub fn editor(&self) -> &Editor {
42
276
        &self.editor
43
276
    }
44

            
45
    /// Direct access to the inner editor.
46
    #[must_use]
47
97
    pub fn as_editor_mut(&mut self) -> &mut Editor {
48
97
        &mut self.editor
49
97
    }
50

            
51
    /// Advance the date by `delta_days` days, preserving the time-of-day component.
52
    ///
53
    /// On parse failure the buffer is replaced with a now-relative step. On
54
    /// date-range overflow the buffer is left unchanged.
55
17
    pub fn step(&mut self, delta_days: i64) {
56
17
        if let Some(new_val) = step_date(self.value(), delta_days) {
57
17
            self.editor.replace_buffer(new_val);
58
        }
59
17
    }
60
}
61

            
62
#[cfg(test)]
63
#[path = "date_tests.rs"]
64
mod tests;