Skip to main content

tui/widgets/
date.rs

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
7use forms::{now_instant, step_date};
8
9use super::editor::Editor;
10
11/// A text field for date entry.
12#[derive(Debug, Clone)]
13pub struct DateWidget {
14    editor: Editor,
15}
16
17/// A date widget pre-seeded with the current instant (RFC3339).
18impl Default for DateWidget {
19    fn default() -> Self {
20        Self {
21            editor: Editor::with_buffer(now_instant()),
22        }
23    }
24}
25
26impl DateWidget {
27    #[must_use]
28    pub fn with_value(value: impl Into<String>) -> Self {
29        Self {
30            editor: Editor::with_buffer(value),
31        }
32    }
33
34    /// Buffer text (the current date string).
35    #[must_use]
36    pub fn value(&self) -> &str {
37        self.editor.buffer()
38    }
39
40    #[must_use]
41    pub fn editor(&self) -> &Editor {
42        &self.editor
43    }
44
45    /// Direct access to the inner editor.
46    #[must_use]
47    pub fn as_editor_mut(&mut self) -> &mut Editor {
48        &mut self.editor
49    }
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    pub fn step(&mut self, delta_days: i64) {
56        if let Some(new_val) = step_date(self.value(), delta_days) {
57            self.editor.replace_buffer(new_val);
58        }
59    }
60}
61
62#[cfg(test)]
63#[path = "date_tests.rs"]
64mod tests;