tix-tracker 0.10.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
502
503
504
505
506
507
508
//! The F3 Cycle mode: cycles grouped chronologically with their statistics.
//!
//! The mode is a pure view + a cursor (`CycleState`): the app builds the
//! [`CycleEntry`] list through [`crate::planning::Planner`] and the cycle store
//! and the widget only groups, renders, and reports the row rectangles it drew
//! so a click selects a cycle.
//!
//! Grouping is chronological and absolute-date based — a cycle is *current*
//! when today sits inside its window (or it has no end date at all), *future*
//! when its start date is still ahead, and *archived* once its due date has
//! passed. It is derived, never stored: the same cycle moves between groups as
//! the clock advances, which is exactly what "current" has to mean.

use ratatui::Frame;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Paragraph};

use crate::app::{Action, App};
use crate::keybindings::{InputContext, TuiAction};

pub use crate::planning::Progress;

/// Where a cycle sits relative to today.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CycleGroup {
    /// Today is inside the cycle's window, or the cycle has no end date.
    Current,
    /// The cycle's start date is still ahead.
    Future,
    /// The cycle's due date has passed.
    Archived,
}

impl CycleGroup {
    /// The three groups, in the order the mode lists them.
    pub const ALL: [Self; 3] = [Self::Current, Self::Future, Self::Archived];

    /// The heading shown above the group.
    pub const fn label(self) -> &'static str {
        match self {
            Self::Current => "Current",
            Self::Future => "Future",
            Self::Archived => "Archived",
        }
    }
}

/// One cycle as the mode lists it: identity, dates, and its issue statistics.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CycleEntry {
    pub name: String,
    pub description: String,
    pub start_date: Option<String>,
    pub due_date: Option<String>,
    pub progress: Progress,
}

impl CycleEntry {
    /// Which chronological group this cycle belongs to on `today`.
    ///
    /// A passed due date wins outright (a cycle is archived the day after it
    /// ends, even if its start is somehow in the future); otherwise a start
    /// date still ahead makes it future; everything else — including the
    /// implicit `Default` with no dates — is current.
    pub fn group(&self, today: &str) -> CycleGroup {
        if self.due_date.as_deref().is_some_and(|due| due < today) {
            CycleGroup::Archived
        } else if self
            .start_date
            .as_deref()
            .is_some_and(|start| start > today)
        {
            CycleGroup::Future
        } else {
            CycleGroup::Current
        }
    }

    /// The mode's one-line row: name, start date, due date. A missing date
    /// renders as `—`, never as an empty column that looks like a rendering
    /// glitch.
    pub fn row_line(&self) -> String {
        let date = |value: &Option<String>| value.clone().unwrap_or_else(|| "—".to_string());
        format!(
            "{}   {} → {}",
            self.name,
            date(&self.start_date),
            date(&self.due_date)
        )
    }
}

/// The mode's cursor state. Session-only; the selected index is over the
/// **entries** (never a group heading), so `j`/`k` walk cycles and nothing
/// else.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct CycleState {
    pub selected: usize,
}

impl CycleState {
    /// Move the cursor, clamped to `len` entries.
    pub fn move_selected(&mut self, delta: isize, len: usize) {
        if len == 0 {
            self.selected = 0;
            return;
        }
        let next = self.selected as isize + delta;
        self.selected = next.clamp(0, len as isize - 1) as usize;
    }

    /// Jump to the first entry of the group `delta` groups away, clamped at the
    /// ends: `h` in the first section and `l` in the last stay in that section
    /// rather than wrapping (tui-cycle-mode).
    ///
    /// Only groups that actually have entries are landing sites. An empty
    /// section renders nothing, so jumping to it would be a keystroke with no
    /// visible effect; skipping it is what "the rendered groups" means.
    pub fn move_group(&mut self, groups: &[CycleGrouping], delta: isize) {
        let starts = group_starts(groups);
        if starts.is_empty() {
            self.selected = 0;
            return;
        }
        // The group holding the cursor: the last one that starts at or before
        // it. A stale index past the end belongs to the last group rather than
        // to a nonexistent one.
        let current = starts
            .iter()
            .rposition(|start| *start <= self.selected)
            .unwrap_or(0);
        let last = starts.len() as isize - 1;
        self.selected = starts[(current as isize + delta).clamp(0, last) as usize];
    }
}

/// The flat index of each non-empty group's first entry, in listing order.
fn group_starts(groups: &[CycleGrouping]) -> Vec<usize> {
    let mut starts = Vec::new();
    let mut offset = 0usize;
    for grouping in groups {
        if grouping.entries.is_empty() {
            continue;
        }
        starts.push(offset);
        offset += grouping.entries.len();
    }
    starts
}

/// One chronological section of the listing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CycleGrouping {
    pub group: CycleGroup,
    pub entries: Vec<CycleEntry>,
}

/// Group `entries` into current/future/archived, each section ordered oldest
/// first (start date, then due date, then name) so the listing reads
/// chronologically top to bottom.
///
/// Empty sections are kept (they carry a count of zero and render as nothing),
/// so the caller can reason about all three without re-deriving them.
pub fn group_entries(entries: Vec<CycleEntry>, today: &str) -> Vec<CycleGrouping> {
    let mut groups: Vec<CycleGrouping> = CycleGroup::ALL
        .iter()
        .map(|group| CycleGrouping {
            group: *group,
            entries: Vec::new(),
        })
        .collect();
    for entry in entries {
        let group = entry.group(today);
        let slot = groups
            .iter_mut()
            .find(|slot| slot.group == group)
            .expect("all three groups exist");
        slot.entries.push(entry);
    }
    for slot in &mut groups {
        slot.entries.sort_by_key(|entry| {
            (
                entry.start_date.clone().unwrap_or_default(),
                entry.due_date.clone().unwrap_or_default(),
                entry.name.clone(),
            )
        });
    }
    groups
}

/// The flat, order-preserving list of entries across the groups — the order
/// the cursor indexes into.
pub fn flat_entries(groups: &[CycleGrouping]) -> Vec<&CycleEntry> {
    groups
        .iter()
        .flat_map(|group| group.entries.iter())
        .collect()
}

fn percent(progress: &Progress) -> usize {
    (progress.done * 100)
        .checked_div(progress.total)
        .unwrap_or(0)
}

/// Draw the Cycle mode into `area` and record one click region per visible row.
pub fn render(app: &App, f: &mut Frame, area: Rect, state: &CycleState, groups: &[CycleGrouping]) {
    let block = Block::default()
        .borders(Borders::ALL)
        .title(" cycles ")
        .border_style(Style::default().fg(Color::Cyan));
    let inner = block.inner(area);
    f.render_widget(block, area);

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Min(3),
            Constraint::Length(2),
            // The focused cycle's flat issue table (shared with the Milestones
            // mode) sits below the listing and its statistics.
            Constraint::Min(4),
            Constraint::Length(1),
        ])
        .split(inner);

    let entries = flat_entries(groups);
    let selected = entries
        .len()
        .checked_sub(1)
        .map_or(0, |last| usize::min(state.selected, last));

    // The list: group headings interleaved with their rows, cursor-highlighted.
    let mut lines: Vec<Line> = Vec::new();
    let mut rows: Vec<(usize, u16)> = Vec::new();
    let mut ordinal = 0usize;
    if entries.is_empty() {
        lines.push(Line::from(Span::styled(
            "No cycles yet — press m to manage cycles and milestones.",
            Style::default().fg(Color::DarkGray),
        )));
    }
    for grouping in groups {
        if grouping.entries.is_empty() {
            continue;
        }
        lines.push(Line::from(Span::styled(
            format!("{} ({})", grouping.group.label(), grouping.entries.len()),
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        )));
        for entry in &grouping.entries {
            let cursor = if ordinal == selected { "> " } else { "  " };
            let style = if ordinal == selected {
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(Color::White)
            };
            lines.push(Line::from(vec![
                Span::styled(cursor, style),
                Span::styled(entry.row_line(), style),
            ]));
            rows.push((ordinal, (lines.len() - 1) as u16));
            ordinal += 1;
        }
    }

    let view_h = chunks[0].height;
    let selected_line = rows
        .iter()
        .find(|(index, _)| *index == selected)
        .map_or(0, |(_, line)| *line);
    let top = selected_line.saturating_sub(view_h.saturating_sub(1));
    let list = Paragraph::new(lines).scroll((top, 0));
    f.render_widget(list, chunks[0]);

    // One click target per entry, computed from the scroll actually applied so a
    // click maps to the row that was painted (the triage/tab pattern).
    for (index, line) in &rows {
        if *line < top || *line - top >= view_h {
            continue;
        }
        let rect = Rect {
            x: chunks[0].x,
            y: chunks[0].y + (*line - top),
            width: chunks[0].width,
            height: 1,
        };
        app.record_region(rect, Action::CycleSelect(*index));
    }

    // Statistics for the selected cycle. An empty cycle is `0/0 (0%)`, never an
    // error and never a division by zero.
    let stats = match entries.get(selected) {
        Some(entry) => vec![
            Line::from(Span::styled(
                format!(" {} ", entry.name),
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD),
            )),
            Line::from(format!(
                " Issues: {}   Completed: {}/{} ({}%)",
                entry.progress.total,
                entry.progress.done,
                entry.progress.total,
                percent(&entry.progress),
            )),
        ],
        None => vec![
            Line::from(Span::styled(
                " Statistics ",
                Style::default().fg(Color::DarkGray),
            )),
            Line::from(" Issues: 0   Completed: 0/0 (0%)"),
        ],
    };
    f.render_widget(Paragraph::new(stats), chunks[1]);

    // The focused cycle's issues, as a flat table: membership is exact string
    // matching on `cycles`, the same rule the statistics above are counted
    // with, and the same table the Milestones mode draws.
    let (issues_title, issues) = match entries.get(selected) {
        Some(entry) => (
            format!("issues — {}", entry.name),
            crate::ui::issue_table::cycle_rows(&app.store, &entry.name),
        ),
        None => ("issues".to_string(), Vec::new()),
    };
    crate::ui::issue_table::render(app, f, chunks[2], &issues_title, &issues);

    let hints = format!(
        "{}: move · {}: group · {}: manage cycles/milestones · {}: close",
        app.bindings.label(InputContext::Cycle, TuiAction::MoveDown),
        app.bindings
            .label(InputContext::Cycle, TuiAction::MoveRight),
        app.bindings.label(InputContext::Cycle, TuiAction::Planning),
        app.bindings.label(InputContext::Cycle, TuiAction::Close),
    );
    f.render_widget(
        Paragraph::new(Line::from(Span::styled(
            hints,
            Style::default().fg(Color::DarkGray),
        ))),
        chunks[3],
    );
}

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

    fn entry(name: &str, start: Option<&str>, due: Option<&str>) -> CycleEntry {
        CycleEntry {
            name: name.to_string(),
            description: String::new(),
            start_date: start.map(str::to_string),
            due_date: due.map(str::to_string),
            progress: Progress { done: 0, total: 0 },
        }
    }

    const TODAY: &str = "2026-10-02";

    #[test]
    fn classifies_current_future_and_archived() {
        let past = entry("Past", Some("2026-01-01"), Some("2026-03-01"));
        let current = entry("Current", Some("2026-09-01"), Some("2026-11-01"));
        let future = entry("Future", Some("2027-01-01"), Some("2027-02-01"));
        assert_eq!(past.group(TODAY), CycleGroup::Archived);
        assert_eq!(current.group(TODAY), CycleGroup::Current);
        assert_eq!(future.group(TODAY), CycleGroup::Future);
    }

    #[test]
    fn a_cycle_with_no_end_date_is_current() {
        let open = entry("Open", Some("2026-01-01"), None);
        assert_eq!(open.group(TODAY), CycleGroup::Current);
        // ...and so is the implicit `Default`, which has no dates at all.
        let default = entry("Default", None, None);
        assert_eq!(default.group(TODAY), CycleGroup::Current);
    }

    #[test]
    fn groups_are_ordered_current_future_archived_and_chronological() {
        let entries = vec![
            entry("Archived B", Some("2025-02-01"), Some("2025-03-01")),
            entry("Future", Some("2027-01-01"), Some("2027-02-01")),
            entry("Current", Some("2026-09-01"), Some("2026-11-01")),
            entry("Archived A", Some("2025-01-01"), Some("2025-01-20")),
        ];
        let groups = group_entries(entries, TODAY);
        let names: Vec<&str> = flat_entries(&groups)
            .into_iter()
            .map(|e| e.name.as_str())
            .collect();
        assert_eq!(
            names,
            vec!["Current", "Future", "Archived A", "Archived B"],
            "current first, then future, then archived oldest-first"
        );
        assert_eq!(groups[0].group, CycleGroup::Current);
        assert_eq!(groups[1].group, CycleGroup::Future);
        assert_eq!(groups[2].group, CycleGroup::Archived);
    }

    #[test]
    fn row_line_shows_name_start_and_due_with_a_dash_for_missing_dates() {
        assert_eq!(
            entry("Sprint", Some("2026-09-01"), Some("2026-09-14")).row_line(),
            "Sprint   2026-09-01 → 2026-09-14"
        );
        assert_eq!(entry("Default", None, None).row_line(), "Default   — → —");
    }

    #[test]
    fn cursor_moves_and_clamps_and_empty_is_zero() {
        let mut state = CycleState::default();
        state.move_selected(1, 2);
        assert_eq!(state.selected, 1);
        state.move_selected(1, 2);
        assert_eq!(state.selected, 1, "clamped at the last entry");
        state.move_selected(-1, 2);
        assert_eq!(state.selected, 0);
        state.move_selected(-1, 2);
        assert_eq!(state.selected, 0, "clamped at the first entry");
        state.move_selected(1, 0);
        assert_eq!(state.selected, 0, "an empty list keeps the cursor at zero");
    }

    #[test]
    fn percent_is_zero_for_an_empty_cycle() {
        assert_eq!(percent(&Progress { done: 0, total: 0 }), 0);
        assert_eq!(percent(&Progress { done: 1, total: 4 }), 25);
        assert_eq!(percent(&Progress { done: 4, total: 4 }), 100);
    }

    #[test]
    fn a_group_jump_lands_on_the_first_entry_of_the_next_rendered_group() {
        let entries = vec![
            entry("Current A", Some("2026-09-01"), Some("2026-11-01")),
            entry("Current B", Some("2026-09-02"), Some("2026-11-02")),
            entry("Future", Some("2027-01-01"), Some("2027-02-01")),
            entry("Archived A", Some("2025-01-01"), Some("2025-02-01")),
            entry("Archived B", Some("2025-02-01"), Some("2025-03-01")),
        ];
        let groups = group_entries(entries, TODAY);
        let mut state = CycleState::default();

        state.move_group(&groups, 1);
        assert_eq!(state.selected, 2, "the first Future entry");
        state.move_group(&groups, 1);
        assert_eq!(state.selected, 3, "the first Archived entry");
        state.move_group(&groups, 1);
        assert_eq!(state.selected, 3, "the last group clamps");
        state.move_group(&groups, -1);
        assert_eq!(state.selected, 2);
        state.move_group(&groups, -1);
        assert_eq!(state.selected, 0, "back to the first Current entry");
        state.move_group(&groups, -1);
        assert_eq!(state.selected, 0, "the first group clamps");
    }

    #[test]
    fn a_group_jump_from_inside_a_group_lands_on_that_groups_first_entry() {
        let entries = vec![
            entry("Current A", Some("2026-09-01"), Some("2026-11-01")),
            entry("Current B", Some("2026-09-02"), Some("2026-11-02")),
            entry("Future", Some("2027-01-01"), Some("2027-02-01")),
        ];
        let groups = group_entries(entries, TODAY);
        let mut state = CycleState { selected: 1 };
        state.move_group(&groups, -1);
        assert_eq!(state.selected, 0, "clamped, and still the first entry");
    }

    #[test]
    fn a_group_jump_skips_an_empty_section_and_survives_an_empty_list() {
        // Current has two entries, Future none, Archived one: the empty one
        // renders nothing, so it is not a landing site.
        let entries = vec![
            entry("Current A", Some("2026-09-01"), Some("2026-11-01")),
            entry("Current B", Some("2026-09-02"), Some("2026-11-02")),
            entry("Archived", Some("2025-01-01"), Some("2025-02-01")),
        ];
        let groups = group_entries(entries, TODAY);
        assert!(groups[1].entries.is_empty(), "Future really is empty");
        let mut state = CycleState::default();
        state.move_group(&groups, 1);
        assert_eq!(
            state.selected, 2,
            "the Archived entry, not the empty Future"
        );

        let mut empty = CycleState { selected: 4 };
        empty.move_group(&[], 1);
        assert_eq!(
            empty.selected, 0,
            "an empty listing keeps the cursor at zero"
        );
    }
}