Skip to main content

mach/
duepicker.rs

1//! Date-and-time picker for the Due field. Both the day and the clock
2//! are set from this UI — the field itself is not free-typed.
3
4use chrono::{Datelike, Local, NaiveDate, Timelike};
5use ratatui::layout::Rect;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum PickerFocus {
9    Calendar,
10    Hour,
11    Minute,
12}
13
14impl PickerFocus {
15    pub fn next(self) -> Self {
16        match self {
17            Self::Calendar => Self::Hour,
18            Self::Hour => Self::Minute,
19            Self::Minute => Self::Calendar,
20        }
21    }
22
23    pub fn prev(self) -> Self {
24        match self {
25            Self::Calendar => Self::Minute,
26            Self::Hour => Self::Calendar,
27            Self::Minute => Self::Hour,
28        }
29    }
30}
31
32/// Hit targets filled in while drawing, so mouse events can find a day
33/// or the hour/minute cells. Matches ratatui's Monthly layout: each day
34/// is three columns (` ` + two-digit day), weeks start on Sunday.
35#[derive(Debug, Default, Clone, Copy)]
36pub struct PickerLayout {
37    pub frame: Rect,
38    /// The day grid only (under the month + weekday headers).
39    pub days: Rect,
40    pub hour: Rect,
41    pub minute: Rect,
42    pub time_row: Rect,
43}
44
45pub struct DuePicker {
46    /// The day under the cursor.
47    pub day: NaiveDate,
48    pub hour: u8,
49    pub minute: u8,
50    pub focus: PickerFocus,
51    /// First digit typed into the focused hour/minute field.
52    entry: Option<u8>,
53    original: String,
54    date_changed: bool,
55    time_changed: bool,
56    /// Last drawn positions for hit-testing.
57    pub layout: PickerLayout,
58}
59
60impl DuePicker {
61    /// Opens on the date/time already in the field, or on now.
62    pub fn new(current: &str) -> Self {
63        let current = current.trim();
64        let now = Local::now();
65        let day = parse_day(current).unwrap_or_else(|| now.date_naive());
66        let (hour, minute) = match crate::due::sort_key_at(current, now.date_naive()) {
67            // Only trust the clock when the stored value actually has one.
68            Some((_, _, _, h, m)) if current.contains(':') => (h as u8, m as u8),
69            _ => (now.hour() as u8, now.minute() as u8),
70        };
71        Self {
72            day,
73            hour,
74            minute,
75            focus: PickerFocus::Calendar,
76            entry: None,
77            original: current.to_string(),
78            date_changed: false,
79            time_changed: false,
80            layout: PickerLayout::default(),
81        }
82    }
83
84    /// True when `(x, y)` is inside the picker frame.
85    pub fn contains(&self, x: u16, y: u16) -> bool {
86        hit(self.layout.frame, x, y)
87    }
88
89    /// Apply a left-click. Returns true when the click was handled.
90    pub fn click(&mut self, x: u16, y: u16) -> bool {
91        let layout = self.layout;
92        if hit(layout.hour, x, y) {
93            self.set_focus(PickerFocus::Hour);
94            return true;
95        }
96        if hit(layout.minute, x, y) {
97            self.set_focus(PickerFocus::Minute);
98            return true;
99        }
100        if let Some(day) = date_at_click(self.day, layout.days, x, y) {
101            self.set_day(day);
102            self.set_focus(PickerFocus::Calendar);
103            return true;
104        }
105        // Click elsewhere inside the frame just focuses the calendar.
106        if self.contains(x, y) {
107            self.set_focus(PickerFocus::Calendar);
108            return true;
109        }
110        false
111    }
112
113    /// Scroll over the picker: calendar months, or hour/minute steps.
114    pub fn scroll(&mut self, x: u16, y: u16, up: bool) -> bool {
115        let layout = self.layout;
116        let delta = if up { 1 } else { -1 };
117        if hit(layout.hour, x, y) || (hit(layout.time_row, x, y) && self.focus == PickerFocus::Hour)
118        {
119            self.set_focus(PickerFocus::Hour);
120            self.bump_hour(delta);
121            return true;
122        }
123        if hit(layout.minute, x, y)
124            || (hit(layout.time_row, x, y) && self.focus == PickerFocus::Minute)
125        {
126            self.set_focus(PickerFocus::Minute);
127            self.bump_minute(delta * 5);
128            return true;
129        }
130        if self.contains(x, y) {
131            self.set_focus(PickerFocus::Calendar);
132            self.move_months(delta);
133            return true;
134        }
135        false
136    }
137
138    /// Preserve the representation the user opened. A missing date or clock
139    /// is only added when the user actually changes that component.
140    pub fn value(&self) -> String {
141        if !self.date_changed && !self.time_changed {
142            if !self.original.is_empty() {
143                return self.original.clone();
144            }
145            return format!(
146                "{} {:02}:{:02}",
147                self.day.format("%Y-%m-%d"),
148                self.hour,
149                self.minute
150            );
151        }
152        let (had_date, had_year, had_time) = original_shape(&self.original);
153        let include_date = had_date || self.date_changed;
154        let include_time = had_time || self.time_changed;
155        if include_date {
156            if include_time {
157                format!(
158                    "{} {:02}:{:02}",
159                    self.day.format("%Y-%m-%d"),
160                    self.hour,
161                    self.minute
162                )
163            } else if had_date && !had_year {
164                self.day.format("%m-%d").to_string()
165            } else {
166                self.day.format("%Y-%m-%d").to_string()
167            }
168        } else {
169            debug_assert!(include_time);
170            format!("{:02}:{:02}", self.hour, self.minute)
171        }
172    }
173
174    pub fn focus_next(&mut self) {
175        self.set_focus(self.focus.next());
176    }
177
178    pub fn focus_prev(&mut self) {
179        self.set_focus(self.focus.prev());
180    }
181
182    fn set_focus(&mut self, focus: PickerFocus) {
183        if focus != self.focus {
184            self.entry = None;
185        }
186        self.focus = focus;
187    }
188
189    pub fn move_days(&mut self, days: i64) {
190        self.entry = None;
191        if let Some(day) = self.day.checked_add_signed(chrono::Duration::days(days)) {
192            self.set_day(day);
193        }
194    }
195
196    pub fn move_months(&mut self, months: i32) {
197        self.entry = None;
198        let (mut year, mut month) = (self.day.year(), self.day.month() as i32 + months);
199        while month < 1 {
200            month += 12;
201            year -= 1;
202        }
203        while month > 12 {
204            month -= 12;
205            year += 1;
206        }
207        // Clamp onto the last day of a shorter month.
208        let day = self.day.day().min(days_in_month(year, month as u32));
209        if let Some(date) = NaiveDate::from_ymd_opt(year, month as u32, day) {
210            self.set_day(date);
211        }
212    }
213
214    /// Jump the day to today; leave the clock as it is.
215    pub fn today(&mut self) {
216        self.set_day(Local::now().date_naive());
217    }
218
219    /// Set the clock to the current time of day.
220    pub fn now_time(&mut self) {
221        self.entry = None;
222        let now = Local::now();
223        self.set_time(now.hour() as u8, now.minute() as u8);
224    }
225
226    pub fn bump_hour(&mut self, delta: i32) {
227        self.entry = None;
228        let h = (self.hour as i32 + delta).rem_euclid(24) as u8;
229        self.set_time(h, self.minute);
230    }
231
232    pub fn bump_minute(&mut self, delta: i32) {
233        self.entry = None;
234        let total = self.hour as i32 * 60 + self.minute as i32 + delta;
235        let total = total.rem_euclid(24 * 60);
236        self.set_time((total / 60) as u8, (total % 60) as u8);
237    }
238
239    /// Type a digit into the clock. On the calendar, jumps to hour first.
240    /// Hour: 0–23 (auto-advances to minute after a complete value).
241    /// Minute: 0–59.
242    pub fn type_digit(&mut self, d: u8) {
243        if d > 9 {
244            return;
245        }
246        if self.focus == PickerFocus::Calendar {
247            self.set_focus(PickerFocus::Hour);
248        }
249        match self.focus {
250            PickerFocus::Hour => self.push_hour_digit(d),
251            PickerFocus::Minute => self.push_minute_digit(d),
252            PickerFocus::Calendar => {}
253        }
254    }
255
256    fn push_hour_digit(&mut self, d: u8) {
257        let Some(first) = self.entry.take() else {
258            self.entry = Some(d);
259            self.set_time(d, self.minute);
260            // 3–9 can only be single-digit hours → commit and move on.
261            if d >= 3 {
262                self.entry = None;
263                self.set_focus(PickerFocus::Minute);
264            }
265            return;
266        };
267        let h = first * 10 + d;
268        self.set_time(if h < 24 { h } else { d }, self.minute);
269        self.set_focus(PickerFocus::Minute);
270    }
271
272    fn push_minute_digit(&mut self, d: u8) {
273        let Some(first) = self.entry.take() else {
274            self.entry = Some(d);
275            self.set_time(self.hour, d);
276            // 6–9 can only be single-digit minutes.
277            if d >= 6 {
278                self.entry = None;
279            }
280            return;
281        };
282        let m = first * 10 + d;
283        self.set_time(self.hour, if m < 60 { m } else { d });
284    }
285
286    fn set_day(&mut self, day: NaiveDate) {
287        if day != self.day {
288            self.day = day;
289            self.date_changed = true;
290        }
291    }
292
293    fn set_time(&mut self, hour: u8, minute: u8) {
294        if (hour, minute) != (self.hour, self.minute) {
295            self.hour = hour;
296            self.minute = minute;
297            self.time_changed = true;
298        }
299    }
300}
301
302fn original_shape(original: &str) -> (bool, bool, bool) {
303    let had_date = original.contains('-');
304    let had_year = original
305        .split_whitespace()
306        .next()
307        .is_some_and(|date| date.split('-').next().is_some_and(|year| year.len() == 4));
308    (had_date, had_year, original.contains(':'))
309}
310
311fn hit(r: Rect, x: u16, y: u16) -> bool {
312    !r.is_empty() && r.contains(ratatui::layout::Position { x, y })
313}
314
315/// Map a click on the Monthly day grid to a calendar date.
316///
317/// Layout (per ratatui-widgets calendar): each of 7 days is three cells
318/// wide (` ` + `dd`), rows are Sunday-based weeks starting from the
319/// Sunday on or before the 1st of the displayed month.
320fn date_at_click(anchor: NaiveDate, days: Rect, x: u16, y: u16) -> Option<NaiveDate> {
321    if !hit(days, x, y) {
322        return None;
323    }
324    let week = (y - days.y) as i64;
325    let col = ((x - days.x) / 3) as i64;
326    if !(0..=6).contains(&col) {
327        return None;
328    }
329    let first = anchor.with_day(1)?;
330    let offset = first.weekday().num_days_from_sunday() as i64;
331    let start = first.checked_sub_signed(chrono::Duration::days(offset))?;
332    start.checked_add_signed(chrono::Duration::days(week * 7 + col))
333}
334
335/// Reads back the shapes mach stores, so reopening the picker lands
336/// on the date that is already set.
337fn parse_day(due: &str) -> Option<NaiveDate> {
338    let (year, month, day, _, _) = crate::due::sort_key(due)?;
339    NaiveDate::from_ymd_opt(year, month, day)
340}
341
342fn days_in_month(year: i32, month: u32) -> u32 {
343    let (next_year, next_month) = if month == 12 {
344        (year + 1, 1)
345    } else {
346        (year, month + 1)
347    };
348    NaiveDate::from_ymd_opt(next_year, next_month, 1)
349        .and_then(|first| first.pred_opt())
350        .map(|last| last.day())
351        .unwrap_or(28)
352}
353
354/// The picker's day as the `time` crate spells it, which is what
355/// ratatui's calendar widget takes.
356pub fn to_time_date(day: NaiveDate) -> Option<time::Date> {
357    let month = time::Month::try_from(day.month() as u8).ok()?;
358    time::Date::from_calendar_date(day.year(), month, day.day() as u8).ok()
359}
360
361#[cfg(test)]
362mod tests {
363    use super::*;
364
365    #[test]
366    fn opens_on_the_date_already_set() {
367        let picker = DuePicker::new("2030-01-02");
368        assert_eq!(picker.day, NaiveDate::from_ymd_opt(2030, 1, 2).unwrap());
369        assert_eq!(picker.value(), "2030-01-02");
370    }
371
372    #[test]
373    fn keeps_the_time_that_was_there() {
374        let picker = DuePicker::new("2030-01-02 09:30");
375        assert_eq!(picker.hour, 9);
376        assert_eq!(picker.minute, 30);
377        assert_eq!(picker.value(), "2030-01-02 09:30");
378    }
379
380    #[test]
381    fn a_bare_time_means_today_at_that_time() {
382        let picker = DuePicker::new("09:30");
383        assert_eq!(picker.day, Local::now().date_naive());
384        assert_eq!(picker.hour, 9);
385        assert_eq!(picker.minute, 30);
386        assert_eq!(picker.value(), "09:30");
387    }
388
389    #[test]
390    fn changing_only_an_existing_component_preserves_due_precision() {
391        let mut date = DuePicker::new("2030-01-02");
392        date.move_days(1);
393        assert_eq!(date.value(), "2030-01-03");
394
395        let mut time = DuePicker::new("09:30");
396        time.bump_minute(5);
397        assert_eq!(time.value(), "09:35");
398
399        let mut yearless = DuePicker::new("08-09");
400        yearless.move_days(1);
401        assert_eq!(yearless.value(), "08-10");
402    }
403
404    #[test]
405    fn changing_a_missing_component_intentionally_adds_it() {
406        let mut date = DuePicker::new("2030-01-02");
407        date.bump_hour(1);
408        assert!(date.value().starts_with("2030-01-02 "));
409
410        let mut time = DuePicker::new("09:30");
411        time.move_days(1);
412        assert!(time.value().ends_with(" 09:30"));
413    }
414
415    #[test]
416    fn walks_days_and_months() {
417        let mut picker = DuePicker::new("2030-01-31");
418        picker.move_days(1);
419        assert_eq!(picker.day, NaiveDate::from_ymd_opt(2030, 2, 1).unwrap());
420        picker.move_months(-1);
421        assert_eq!(picker.day, NaiveDate::from_ymd_opt(2030, 1, 1).unwrap());
422    }
423
424    #[test]
425    fn clamps_onto_a_shorter_month() {
426        let mut picker = DuePicker::new("2030-01-31");
427        picker.move_months(1);
428        assert_eq!(
429            picker.day,
430            NaiveDate::from_ymd_opt(2030, 2, 28).unwrap(),
431            "January 31st has no February counterpart"
432        );
433    }
434
435    #[test]
436    fn bumps_hour_and_minute_wrapping() {
437        let mut picker = DuePicker::new("2030-01-02 23:55");
438        picker.bump_hour(1);
439        assert_eq!((picker.hour, picker.minute), (0, 55));
440        picker.bump_minute(10);
441        assert_eq!((picker.hour, picker.minute), (1, 5));
442        picker.bump_minute(-10);
443        assert_eq!((picker.hour, picker.minute), (0, 55));
444    }
445
446    #[test]
447    fn tab_walks_focus() {
448        let mut picker = DuePicker::new("");
449        assert_eq!(picker.focus, PickerFocus::Calendar);
450        picker.focus_next();
451        assert_eq!(picker.focus, PickerFocus::Hour);
452        picker.focus_next();
453        assert_eq!(picker.focus, PickerFocus::Minute);
454        picker.focus_next();
455        assert_eq!(picker.focus, PickerFocus::Calendar);
456    }
457
458    #[test]
459    fn click_picks_a_day_from_the_grid() {
460        // August 2026 starts on Saturday → Sunday before is July 26.
461        let mut picker = DuePicker::new("2026-08-05 12:00");
462        picker.layout.days = Rect {
463            x: 10,
464            y: 5,
465            width: 21,
466            height: 6,
467        };
468        // Week 0, column 3 (Wed) → July 29 (surrounding month).
469        assert!(picker.click(10 + 3 * 3 + 1, 5));
470        assert_eq!(picker.day, NaiveDate::from_ymd_opt(2026, 7, 29).unwrap());
471
472        // Reset to August so the grid is that month again.
473        picker.day = NaiveDate::from_ymd_opt(2026, 8, 5).unwrap();
474        // Week 1, column 3 → August 5.
475        assert!(picker.click(10 + 3 * 3 + 1, 6));
476        assert_eq!(picker.day, NaiveDate::from_ymd_opt(2026, 8, 5).unwrap());
477    }
478
479    #[test]
480    fn click_focuses_hour_and_minute() {
481        let mut picker = DuePicker::new("2026-08-05 12:00");
482        picker.layout.hour = Rect {
483            x: 5,
484            y: 10,
485            width: 2,
486            height: 1,
487        };
488        picker.layout.minute = Rect {
489            x: 8,
490            y: 10,
491            width: 2,
492            height: 1,
493        };
494        assert!(picker.click(5, 10));
495        assert_eq!(picker.focus, PickerFocus::Hour);
496        assert!(picker.click(8, 10));
497        assert_eq!(picker.focus, PickerFocus::Minute);
498    }
499
500    #[test]
501    fn digits_type_hour_and_minute() {
502        let mut picker = DuePicker::new("2030-01-02 00:00");
503        picker.focus = PickerFocus::Hour;
504        picker.type_digit(1);
505        picker.type_digit(5);
506        assert_eq!(picker.hour, 15);
507        assert_eq!(picker.focus, PickerFocus::Minute);
508        picker.type_digit(3);
509        picker.type_digit(0);
510        assert_eq!(picker.minute, 30);
511        assert_eq!(picker.value(), "2030-01-02 15:30");
512    }
513
514    #[test]
515    fn single_digit_hour_auto_advances() {
516        let mut picker = DuePicker::new("2030-01-02 00:00");
517        picker.focus = PickerFocus::Hour;
518        picker.type_digit(9);
519        assert_eq!(picker.hour, 9);
520        assert_eq!(picker.focus, PickerFocus::Minute);
521    }
522
523    #[test]
524    fn digit_on_calendar_starts_hour() {
525        let mut picker = DuePicker::new("2030-01-02 08:00");
526        assert_eq!(picker.focus, PickerFocus::Calendar);
527        picker.type_digit(1);
528        assert_eq!(picker.focus, PickerFocus::Hour);
529        assert_eq!(picker.hour, 1);
530    }
531}