tix-tracker 0.12.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
//! A reusable calendar date picker popup.
//!
//! Date fields across the TUI (issue create/edit form, planning form, filter
//! modal) are picker-only: values can only be set as a valid `YYYY-MM-DD`
//! date, never typed free-form. Pressing `F2` on a focused date field opens
//! this modal; `Enter` writes the highlighted date back, `Esc` cancels, and
//! `c`/`Delete` clears the field.
//!
//! Rendering is delegated to [`ratatui::widgets::calendar::Monthly`]; this
//! module owns the selection state, key handling, and popup layout.

use crossterm::event::KeyCode;
use ratatui::Frame;
use ratatui::layout::{Alignment, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::Line;
use ratatui::widgets::calendar::{CalendarEventStore, Monthly};
use ratatui::widgets::{Block, Borders, Clear, Paragraph};
use time::{Date, Duration, Month};

/// The outcome of routing a key event to a [`DatePicker`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DatePickerEvent {
    /// The key did not resolve the picker (movement / no-op).
    None,
    /// The user dismissed the picker (`Esc`).
    Cancelled,
    /// The user confirmed the highlighted date (`Enter`), as `YYYY-MM-DD`.
    Selected(String),
    /// The user cleared the field (`c` / `Delete`).
    Cleared,
}

/// Pointer input resolved against the picker popup (D5/D6): a specific day
/// cell or a chrome control. Mapped to the same outcome the equivalent key
/// would produce — selecting a date, paging months, or submitting.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DatePickerHit {
    /// A day cell, as `YYYY-MM-DD` (equivalent to navigating there + Enter).
    Day(String),
    /// The previous-month control (`PageUp`).
    PrevMonth,
    /// The next-month control (`PageDown`).
    NextMonth,
    /// The submit control (`Enter` on the highlighted date).
    Submit,
}

/// A calendar popup for picking a single date.
#[derive(Debug, Clone)]
pub struct DatePicker {
    /// First day of the month currently displayed.
    view: Date,
    /// The highlighted date.
    selected: Date,
}

impl DatePicker {
    /// Open the picker on `value` when it parses as a valid `YYYY-MM-DD` date,
    /// otherwise on today's date.
    pub fn new(value: &str) -> Self {
        let selected = parse_date(value).unwrap_or_else(today_date);
        Self {
            view: first_of_month(selected),
            selected,
        }
    }

    /// The currently highlighted date as `YYYY-MM-DD`.
    pub fn selected(&self) -> String {
        format_date(self.selected)
    }

    /// Route a key press, returning the resulting [`DatePickerEvent`].
    pub fn handle_key(&mut self, code: KeyCode) -> DatePickerEvent {
        match code {
            KeyCode::Esc | KeyCode::Char('q') | KeyCode::Char('Q') => {
                return DatePickerEvent::Cancelled;
            }
            KeyCode::Enter => return DatePickerEvent::Selected(self.selected()),
            KeyCode::Delete | KeyCode::Char('c') | KeyCode::Char('C') => {
                return DatePickerEvent::Cleared;
            }
            KeyCode::Left | KeyCode::Char('h') => self.shift_days(-1),
            KeyCode::Right | KeyCode::Char('l') => self.shift_days(1),
            KeyCode::Up | KeyCode::Char('k') => self.shift_days(-7),
            KeyCode::Down | KeyCode::Char('j') => self.shift_days(7),
            KeyCode::PageUp => self.shift_months(-1),
            KeyCode::PageDown => self.shift_months(1),
            KeyCode::Char('[') => self.shift_years(-1),
            KeyCode::Char(']') => self.shift_years(1),
            _ => {}
        }
        DatePickerEvent::None
    }

    fn shift_days(&mut self, days: i64) {
        let delta = Duration::days(days);
        let next = if days >= 0 {
            self.selected.checked_add(delta)
        } else {
            self.selected.checked_sub(-delta)
        };
        if let Some(date) = next {
            self.set_selected(date);
        }
    }

    fn shift_months(&mut self, months: i32) {
        let month0 = i32::from(u8::from(self.selected.month())) - 1 + months;
        let year = self.selected.year() + month0.div_euclid(12);
        let month = Month::try_from((month0.rem_euclid(12) + 1) as u8).expect("1..=12");
        let day = self.selected.day().min(month.length(year));
        if let Ok(date) = Date::from_calendar_date(year, month, day) {
            self.set_selected(date);
        }
    }

    fn shift_years(&mut self, years: i32) {
        let year = self.selected.year() + years;
        let month = self.selected.month();
        let day = self.selected.day().min(month.length(year));
        if let Ok(date) = Date::from_calendar_date(year, month, day) {
            self.set_selected(date);
        }
    }

    fn set_selected(&mut self, date: Date) {
        self.selected = date;
        self.view = first_of_month(date);
    }

    /// Jump the highlight straight to `date` (a day-cell click, D5/D6) —
    /// the same state navigating there and pressing Enter would leave.
    pub fn select_date(&mut self, date: Date) {
        self.set_selected(date);
    }

    /// `select_date` for a `YYYY-MM-DD` string (day-cell click payload).
    pub fn select_date_str(&mut self, value: &str) {
        if let Some(date) = parse_date(value) {
            self.set_selected(date);
        }
    }

    /// Shift the view by `months` months (Prev/Next controls, `PageUp`/
    /// `PageDown` equivalents).
    pub fn shift_month(&mut self, months: i32) {
        self.shift_months(months);
    }

    /// The popup rectangle for `area`, exactly matching what [`DatePicker::render`]
    /// draws against. Exposed so the pointer can be mapped onto the calendar.
    pub fn popup_rect(&self, area: Rect) -> Rect {
        let width = 64.min(area.width);
        let height = (u16::from(weeks_for(self.view)) + 6).min(area.height);
        centered(area, width, height)
    }

    /// The date under `(x, y)` when it falls on a calendar day cell within the
    /// popup for `area`, following the same Sunday-grid layout ratatui's
    /// `Monthly` widget uses (gutter + 2-char day per column, week rows under
    /// the month/weekday headers). Returns `None` for popup chrome or outside.
    pub fn date_at(&self, area: Rect, x: u16, y: u16) -> Option<Date> {
        let rect = self.popup_rect(area);
        let inner_x = rect.x + 1;
        let days_y = rect.y + 1 + 1 + 1; // border + month header + weekday header
        if y < days_y || x < inner_x {
            return None;
        }
        let col = (x - inner_x) / 3;
        if col > 6 {
            return None;
        }
        let row = y - days_y;
        if row >= u16::from(weeks_for(self.view)) {
            return None;
        }
        let first = self.view.replace_day(1).ok()?;
        let offset = Duration::days(i64::from(first.weekday().number_days_from_sunday()));
        first
            .checked_sub(offset)
            .and_then(|s| s.checked_add(Duration::days(i64::from(row * 7 + col))))
    }

    /// Render the popup centered over `area`.
    pub fn render(&self, f: &mut Frame, area: Rect) {
        let bindings =
            crate::keybindings::KeyBindings::resolve(&crate::keybindings::KeyBindings::default())
                .expect("built-in bindings are valid");
        self.render_with_bindings(
            f,
            area,
            &bindings,
            crate::keybindings::InputContext::DatePicker,
        );
    }

    pub fn render_with_bindings(
        &self,
        f: &mut Frame,
        area: Rect,
        bindings: &crate::keybindings::EffectiveBindings,
        context: crate::keybindings::InputContext,
    ) {
        let mut events = CalendarEventStore::default();
        events.add(
            self.selected,
            Style::default()
                .fg(Color::Black)
                .bg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        );
        events.add(
            today_date(),
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        );

        let monthly = Monthly::new(self.view, events)
            .show_surrounding(Style::default().fg(Color::DarkGray))
            .show_weekdays_header(Style::default().add_modifier(Modifier::ITALIC))
            .show_month_header(Style::default().add_modifier(Modifier::BOLD))
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .title(" Pick a date ")
                    .style(Style::default().fg(Color::Cyan)),
            );

        let width = monthly.width().max(64).min(area.width);
        let height = (monthly.height() + 2).min(area.height);
        let rect = centered(area, width, height);
        let calendar_area = Rect {
            height: height.saturating_sub(2),
            ..rect
        };
        let hint_area = Rect {
            y: rect.y + height.saturating_sub(1),
            height: 1,
            ..rect
        };

        f.render_widget(Clear, rect);
        f.render_widget(monthly, calendar_area);
        let move_days = format!(
            "{}/{} {}/{} move",
            bindings.label(context, crate::keybindings::TuiAction::MoveLeft),
            bindings.label(context, crate::keybindings::TuiAction::MoveRight),
            bindings.label(context, crate::keybindings::TuiAction::MoveUp),
            bindings.label(context, crate::keybindings::TuiAction::MoveDown),
        );
        let months = format!(
            "{}/{} month",
            bindings.label(context, crate::keybindings::TuiAction::PreviousMonth),
            bindings.label(context, crate::keybindings::TuiAction::NextMonth),
        );
        let years = format!(
            "{}/{} year",
            bindings.label(context, crate::keybindings::TuiAction::PreviousYear),
            bindings.label(context, crate::keybindings::TuiAction::NextYear),
        );
        f.render_widget(
            Paragraph::new(Line::from(format!(
                "{move_days} \u{b7} {months} \u{b7} {years} \u{b7} {} ok \u{b7} {} clear \u{b7} {} cancel",
                bindings.label(context, crate::keybindings::TuiAction::Submit),
                bindings.label(context, crate::keybindings::TuiAction::Reset),
                bindings.label(context, crate::keybindings::TuiAction::Cancel),
            )))
            .alignment(Alignment::Center)
            .style(Style::default().fg(Color::DarkGray)),
            hint_area,
        );
    }
}

/// Center a `width`x`height` rect inside `area`, clamped to fit.
fn centered(area: Rect, width: u16, height: u16) -> Rect {
    let width = width.min(area.width);
    let height = height.min(area.height);
    Rect::new(
        area.x + (area.width - width) / 2,
        area.y + (area.height - height) / 2,
        width,
        height,
    )
}

fn first_of_month(date: Date) -> Date {
    Date::from_calendar_date(date.year(), date.month(), 1).expect("day 1 is always valid")
}

/// Number of Sunday-based week rows needed to render `date`'s month, mirroring
/// ratatui's `Monthly` calendar widget layout (used for hit geometry).
fn weeks_for(date: Date) -> u8 {
    let first = first_of_month(date);
    let last = first
        .replace_day(first.month().length(first.year()))
        .expect("last day of month is always valid");
    last.sunday_based_week()
        .saturating_sub(first.sunday_based_week())
        + 1
}

/// Parse a `YYYY-MM-DD` string that already passed [`crate::model::validate_date`].
fn parse_date(value: &str) -> Option<Date> {
    if !crate::model::validate_date(value) {
        return None;
    }
    let year: i32 = value.get(0..4)?.parse().ok()?;
    let month: u8 = value.get(5..7)?.parse().ok()?;
    let day: u8 = value.get(8..10)?.parse().ok()?;
    Date::from_calendar_date(year, Month::try_from(month).ok()?, day).ok()
}

/// Whether `value` is a complete, valid `YYYY-MM-DD` date.
pub fn is_complete_date(value: &str) -> bool {
    crate::model::validate_date(value)
}

/// Apply one masked-edit keystroke to a `YYYY-MM-DD` field.
///
/// Only digits are meaningful; the `-` separators are inserted automatically.
/// Returns `None` when `c` is not accepted. `current` may be empty, partial,
/// or a full date; when it is already complete the new digit starts a fresh
/// value (so typing over an existing date replaces it).
pub fn type_date(current: &str, c: char) -> Option<String> {
    if c.is_ascii_digit() {
        let base = if is_complete_date(current) {
            ""
        } else {
            current
        };
        let mut digits = digits_of(base);
        if digits.len() >= 8 {
            return Some(format_digits(&digits));
        }
        digits.push(c);
        Some(format_digits(&digits))
    } else if c == '-' {
        let base = if is_complete_date(current) {
            ""
        } else {
            current
        };
        Some(format_digits(&digits_of(base)))
    } else {
        None
    }
}

/// Remove the last masked-edit digit from a `YYYY-MM-DD` field.
pub fn backspace_date(current: &str) -> String {
    let mut digits = digits_of(current);
    digits.pop();
    format_digits(&digits)
}

fn digits_of(value: &str) -> String {
    value.chars().filter(char::is_ascii_digit).collect()
}

fn format_digits(digits: &str) -> String {
    let mut out = String::new();
    for (i, ch) in digits.chars().take(8).enumerate() {
        if i == 4 || i == 6 {
            out.push('-');
        }
        out.push(ch);
    }
    out
}

fn today_date() -> Date {
    parse_date(&crate::model::today()).unwrap_or_else(|| {
        Date::from_calendar_date(1970, Month::January, 1).expect("epoch is valid")
    })
}

pub fn format_date(date: Date) -> String {
    format!(
        "{:04}-{:02}-{:02}",
        date.year(),
        u8::from(date.month()),
        date.day()
    )
}

#[cfg(test)]
mod tests {
    #[allow(clippy::wildcard_imports)]
    use super::*;

    #[test]
    fn opens_on_valid_value() {
        let picker = DatePicker::new("2026-03-15");
        assert_eq!(picker.selected(), "2026-03-15");
        assert_eq!(
            picker.view,
            first_of_month(parse_date("2026-03-15").unwrap())
        );
    }

    #[test]
    fn opens_on_today_for_invalid_value() {
        let picker = DatePicker::new("not-a-date");
        assert_eq!(picker.selected(), crate::model::today());
    }

    #[test]
    fn enter_selects_highlighted_date() {
        let mut picker = DatePicker::new("2026-03-15");
        assert_eq!(
            picker.handle_key(KeyCode::Enter),
            DatePickerEvent::Selected("2026-03-15".into())
        );
    }

    #[test]
    fn esc_cancels_and_c_clears() {
        let mut picker = DatePicker::new("2026-03-15");
        assert_eq!(picker.handle_key(KeyCode::Esc), DatePickerEvent::Cancelled);
        assert_eq!(
            picker.handle_key(KeyCode::Char('c')),
            DatePickerEvent::Cleared
        );
    }

    #[test]
    fn day_week_and_month_navigation() {
        let mut picker = DatePicker::new("2026-03-15");
        picker.handle_key(KeyCode::Right);
        assert_eq!(picker.selected(), "2026-03-16");
        picker.handle_key(KeyCode::Down);
        assert_eq!(picker.selected(), "2026-03-23");
        picker.handle_key(KeyCode::PageDown);
        assert_eq!(picker.selected(), "2026-04-23");
        picker.handle_key(KeyCode::PageUp);
        assert_eq!(picker.selected(), "2026-03-23");
    }

    #[test]
    fn month_shift_clamps_day() {
        let mut picker = DatePicker::new("2026-01-31");
        picker.handle_key(KeyCode::PageDown);
        assert_eq!(picker.selected(), "2026-02-28");
    }

    #[test]
    fn year_shift_clamps_leap_day() {
        let mut picker = DatePicker::new("2024-02-29");
        picker.handle_key(KeyCode::Char(']'));
        assert_eq!(picker.selected(), "2025-02-28");
    }

    #[test]
    fn mask_typing_inserts_separators() {
        let mut value = String::new();
        for c in "20260910".chars() {
            value = type_date(&value, c).unwrap();
        }
        assert_eq!(value, "2026-09-10");
        assert!(is_complete_date(&value));
    }

    #[test]
    fn mask_typing_a_dash_is_a_noop() {
        let value = type_date("2026", '-').unwrap();
        assert_eq!(value, "2026");
    }

    #[test]
    fn mask_rejects_letters_and_extra_digits() {
        assert_eq!(type_date("2026", 'x'), None);
        let full = type_date("2026-09-10", '5').unwrap();
        assert_eq!(full, "5", "typing over a complete date replaces it");
    }

    #[test]
    fn mask_backspace_removes_last_digit() {
        assert_eq!(backspace_date("2026-09-1"), "2026-09");
        assert_eq!(backspace_date("2026-09"), "2026-0");
        assert_eq!(backspace_date("2026"), "202");
    }

    #[test]
    fn render_smoke() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let picker = DatePicker::new("2026-03-15");
        terminal.draw(|f| picker.render(f, f.area())).unwrap();
        let buffer = terminal.backend().buffer().clone();
        let text: String = buffer.content().iter().map(|c| c.symbol()).collect();
        assert!(text.contains("Pick a date"));
        assert!(text.contains("2026"));
    }
}