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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
//! The issue **action menu**: one grouped, filterable list of everything that can
//! be done with the card under the board cursor.
//!
//! Opened by `Enter`, by a plain left click, and by right-click (which adds the
//! board footer), so the keyboard and the pointer read the same list. The widget
//! owns the query, the filtered order and the cursor; activation is App-owned and
//! routes through the same semantic action path the keyboard uses.
//!
//! Filtering follows the help overlay's rule exactly: literal substring first,
//! then `crate::search::fuzzy_score` as a fallback, with a `(fuzzy)` marker. The
//! tool therefore has one notion of "fuzzy", not a second one that behaves
//! almost the same.

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::Frame;
use ratatui::layout::Rect;
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Clear, Paragraph};

/// Which block of the menu an entry belongs to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ActionGroup {
    Move,
    Open,
    Content,
    Destructive,
    Marks,
    Triage,
    Board,
}

impl ActionGroup {
    pub const fn label(self) -> &'static str {
        match self {
            Self::Move => "Move",
            Self::Open => "Open",
            Self::Content => "Content",
            Self::Destructive => "Destructive",
            Self::Marks => "Batch",
            Self::Triage => "Triage",
            Self::Board => "Board",
        }
    }
}

/// What a menu entry runs.
///
/// Every variant is an *identity*: the App's one dispatcher turns it into the
/// same method a key press calls. Parameterised variants (`MoveTo`, `Mark`,
/// `Triage`) carry the target so the menu can name it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IssueAction {
    OpenDetail,
    EditInEditor,
    ViewIssue,
    OpenAgent,
    CloneIssue,
    OpenMentions,
    RelatedPicker,
    FollowRelated,
    MoveTo {
        column: String,
    },
    Comment,
    AttachAsset,
    NewRelationship,
    Relationships,
    EditRelationship {
        id: String,
    },
    RemoveRelationship {
        id: String,
    },
    SetParent,
    RecordHealth,
    AddTimeEntry,
    Archive,
    Restore,
    Delete,
    Mark {
        on: bool,
    },
    Bulk {
        action: crate::ui::bulk::BatchAction,
    },
    ClearMarks,
    Triage {
        decision: crate::triage::DecisionKind,
    },
    RefreshBoard,
}

/// One rendered entry: its semantic action, its label, its group, and the
/// effective shortcut when one exists.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ActionMenuItem {
    pub action: IssueAction,
    pub label: String,
    pub group: ActionGroup,
    pub shortcut: Option<String>,
    pub danger: bool,
}

impl ActionMenuItem {
    pub fn new(action: IssueAction, label: impl Into<String>, group: ActionGroup) -> Self {
        Self {
            action,
            label: label.into(),
            group,
            shortcut: None,
            danger: false,
        }
    }

    pub fn shortcut(mut self, shortcut: impl Into<String>) -> Self {
        self.shortcut = Some(shortcut.into());
        self
    }

    pub fn danger(mut self, danger: bool) -> Self {
        self.danger = danger;
        self
    }

    fn haystack(&self) -> String {
        let shortcut = self.shortcut.as_deref().unwrap_or("");
        format!("{} {} {}", self.group.label(), self.label, shortcut).to_lowercase()
    }
}

/// The outcome of routing a key event to the menu.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MenuEvent {
    /// The key moved the cursor, changed the query, or was a no-op.
    None,
    /// The user dismissed the menu (`Esc` on the root page).
    Dismissed,
    /// The user confirmed an item; the index addresses the current page's items.
    Selected(usize),
}

/// One page of the menu. The root page is the issue's action list; a submenu is
/// pushed by an entry that has more than one target (relationships today).
#[derive(Debug, Clone)]
struct MenuPage {
    title: String,
    items: Vec<ActionMenuItem>,
    query: String,
    selected: usize,
    visible: Vec<usize>,
    fuzzy: bool,
}

impl MenuPage {
    fn new(title: impl Into<String>, items: Vec<ActionMenuItem>) -> Self {
        let mut page = Self {
            title: title.into(),
            items,
            query: String::new(),
            selected: 0,
            visible: Vec::new(),
            fuzzy: false,
        };
        page.refilter();
        page
    }

    fn refilter(&mut self) {
        let query = self.query.trim().to_lowercase();
        self.visible.clear();
        self.fuzzy = false;
        if query.is_empty() {
            self.visible.extend(0..self.items.len());
        } else {
            let literal: Vec<usize> = self
                .items
                .iter()
                .enumerate()
                .filter(|(_, item)| item.haystack().contains(&query))
                .map(|(index, _)| index)
                .collect();
            if literal.is_empty() {
                self.fuzzy = true;
                // Best first; `sort_by` is stable, so equal scores keep the
                // declared order — the order the menu is normally read in.
                let mut scored: Vec<(u32, usize)> = self
                    .items
                    .iter()
                    .enumerate()
                    .filter_map(|(index, item)| {
                        crate::search::fuzzy_score(&query, &item.haystack())
                            .map(|score| (score, index))
                    })
                    .collect();
                scored.sort_by_key(|(score, _)| std::cmp::Reverse(*score));
                self.visible
                    .extend(scored.into_iter().map(|(_, index)| index));
            } else {
                self.visible = literal;
            }
        }
        self.selected = self.selected.min(self.visible.len().saturating_sub(1));
    }

    fn selected_item(&self) -> Option<&ActionMenuItem> {
        self.visible
            .get(self.selected)
            .and_then(|index| self.items.get(*index))
    }

    fn move_by(&mut self, delta: i32) {
        if self.visible.is_empty() {
            return;
        }
        let last = self.visible.len() - 1;
        let next = self.selected as i32 + delta;
        self.selected = next.clamp(0, last as i32) as usize;
    }

    /// Rows in draw order: a group header, then its items.
    fn rows(&self) -> Vec<Row> {
        let mut rows = Vec::new();
        let mut last: Option<ActionGroup> = None;
        for index in &self.visible {
            let item = &self.items[*index];
            if last != Some(item.group) {
                rows.push(Row::Header(item.group));
                last = Some(item.group);
            }
            rows.push(Row::Item(*index));
        }
        rows
    }

    fn selected_index(&self) -> Option<usize> {
        self.visible.get(self.selected).copied()
    }
}

/// One drawn row of a page.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Row {
    Header(ActionGroup),
    Item(usize),
}

/// The action menu: a stack of pages, a query per page, and the last-drawn
/// window offset so pointer hit-testing agrees with what was rendered.
#[derive(Debug, Clone)]
pub struct ActionMenu {
    pages: Vec<MenuPage>,
    offset: std::cell::Cell<usize>,
}

impl ActionMenu {
    pub fn new(items: Vec<ActionMenuItem>) -> Self {
        let mut menu = Self {
            pages: vec![MenuPage::new("Actions", items)],
            offset: std::cell::Cell::new(0),
        };
        // `Open detail` is the preselected entry even though the Move group is
        // drawn first, so `Enter` `Enter` reproduces the old `Enter`.
        if let Some(page) = menu.pages.last_mut()
            && let Some(position) = page
                .visible
                .iter()
                .position(|index| page.items[*index].action == IssueAction::OpenDetail)
        {
            page.selected = position;
        }
        menu
    }

    fn page(&self) -> &MenuPage {
        self.pages.last().expect("action menu always has a page")
    }

    fn page_mut(&mut self) -> &mut MenuPage {
        self.pages
            .last_mut()
            .expect("action menu always has a page")
    }

    pub fn items(&self) -> &[ActionMenuItem] {
        &self.page().items
    }

    pub fn query(&self) -> &str {
        &self.page().query
    }

    pub fn is_fuzzy(&self) -> bool {
        self.page().fuzzy
    }

    pub fn visible_len(&self) -> usize {
        self.page().visible.len()
    }

    /// The cursor's position in the filtered list.
    pub fn selected_position(&self) -> usize {
        self.page().selected
    }

    pub fn selected_item(&self) -> Option<&ActionMenuItem> {
        self.page().selected_item()
    }

    pub fn item(&self, index: usize) -> Option<&ActionMenuItem> {
        self.page().items.get(index)
    }

    /// Push a submenu. Its own query starts empty, so the parent filter does not
    /// silently hide rows in a list the reader has not seen yet.
    pub fn push(&mut self, title: impl Into<String>, items: Vec<ActionMenuItem>) {
        self.pages.push(MenuPage::new(title, items));
        self.offset.set(0);
    }

    /// Return to the parent page. `false` when this is already the root.
    pub fn pop(&mut self) -> bool {
        if self.pages.len() <= 1 {
            return false;
        }
        self.pages.pop();
        self.offset.set(0);
        true
    }

    pub fn title(&self) -> &str {
        &self.page().title
    }

    pub fn handle_key(&mut self, key: KeyEvent) -> MenuEvent {
        match key.code {
            KeyCode::Esc => {
                if self.pop() {
                    MenuEvent::None
                } else {
                    MenuEvent::Dismissed
                }
            }
            KeyCode::Left if self.pop() => MenuEvent::None,
            KeyCode::Enter => self
                .page()
                .selected_index()
                .map(MenuEvent::Selected)
                .unwrap_or(MenuEvent::None),
            KeyCode::Up => {
                self.page_mut().move_by(-1);
                MenuEvent::None
            }
            KeyCode::Down => {
                self.page_mut().move_by(1);
                MenuEvent::None
            }
            KeyCode::PageUp => {
                self.page_mut().move_by(-8);
                MenuEvent::None
            }
            KeyCode::PageDown => {
                self.page_mut().move_by(8);
                MenuEvent::None
            }
            KeyCode::Backspace => {
                self.page_mut().query.pop();
                self.page_mut().selected = 0;
                self.page_mut().refilter();
                MenuEvent::None
            }
            KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.page_mut().query.clear();
                self.page_mut().selected = 0;
                self.page_mut().refilter();
                MenuEvent::None
            }
            KeyCode::Char(c)
                if !key.modifiers.contains(KeyModifiers::CONTROL)
                    && !key.modifiers.contains(KeyModifiers::ALT) =>
            {
                self.page_mut().query.push(c);
                self.page_mut().selected = 0;
                self.page_mut().refilter();
                MenuEvent::None
            }
            _ => MenuEvent::None,
        }
    }

    /// The popup rect for `area`, size clamped to the content and the area.
    pub fn bounds(&self, area: Rect) -> Rect {
        let rows = self.page().rows();
        let width = rows
            .iter()
            .map(|row| match row {
                Row::Header(group) => group.label().chars().count(),
                Row::Item(index) => {
                    let item = &self.page().items[*index];
                    item.label.chars().count()
                        + item
                            .shortcut
                            .as_deref()
                            .map_or(0, |value| value.chars().count() + 2)
                }
            })
            .max()
            .unwrap_or(0)
            .max(self.title().chars().count())
            .saturating_add(6);
        // Borders + the footer line.
        let height = (rows.len() as u16 + 3).min(area.height);
        Rect::new(
            area.x + (area.width.saturating_sub(width as u16)) / 2,
            area.y + (area.height.saturating_sub(height)) / 2,
            (width as u16).min(area.width),
            height,
        )
    }

    /// The row list, shared by the renderer and the pointer handler.
    pub fn rows(&self) -> Vec<Row> {
        self.page().rows()
    }

    pub fn window_offset(&self) -> usize {
        self.offset.get()
    }

    /// The item under a terminal cell, if the cell is an item row.
    pub fn hit(&self, area: Rect, x: u16, y: u16) -> Option<usize> {
        let bounds = self.bounds(area);
        if x < bounds.x || x >= bounds.x + bounds.width {
            return None;
        }
        if y <= bounds.y || y >= bounds.y + bounds.height.saturating_sub(1) {
            return None;
        }
        let row = usize::from(y - bounds.y - 1) + self.offset.get();
        match self.rows().get(row) {
            Some(Row::Item(index)) => Some(*index),
            _ => None,
        }
    }

    /// Render the current page, keeping the selected item inside the window.
    pub fn render(&self, f: &mut Frame, area: Rect) {
        let rect = self.bounds(area);
        if rect.width < 6 || rect.height < 3 {
            return;
        }
        f.render_widget(Clear, rect);
        let rows = self.page().rows();
        let visible_rows = usize::from(rect.height.saturating_sub(3));
        let selected_index = self.page().selected_index();
        let selected_row = rows
            .iter()
            .position(|row| matches!(row, Row::Item(index) if Some(*index) == selected_index))
            .unwrap_or(0);
        let mut offset = self.offset.get();
        if selected_row < offset {
            offset = selected_row;
        } else if visible_rows > 0 && selected_row >= offset + visible_rows {
            offset = selected_row + 1 - visible_rows;
        }
        offset = offset.min(rows.len().saturating_sub(visible_rows));
        self.offset.set(offset);

        let inner = usize::from(rect.width.saturating_sub(2));
        let mut lines: Vec<Line<'static>> = Vec::new();
        for (row_index, row) in rows.iter().enumerate().skip(offset).take(visible_rows) {
            match row {
                Row::Header(group) => {
                    lines.push(Line::from(Span::styled(
                        group.label().to_ascii_uppercase(),
                        Style::default()
                            .fg(Color::Yellow)
                            .add_modifier(Modifier::BOLD),
                    )));
                }
                Row::Item(index) => {
                    let item = &self.page().items[*index];
                    let selected = row_index == selected_row;
                    let mut style = Style::default();
                    if item.danger {
                        style = style.fg(Color::Red);
                    }
                    if selected {
                        style = style
                            .bg(Color::DarkGray)
                            .fg(if item.danger {
                                Color::Red
                            } else {
                                Color::White
                            })
                            .add_modifier(Modifier::BOLD);
                    }
                    let shortcut = item.shortcut.clone().unwrap_or_default();
                    let gap = inner
                        .saturating_sub(item.label.chars().count())
                        .saturating_sub(shortcut.chars().count());
                    let mut spans = vec![
                        Span::styled(item.label.clone(), style),
                        Span::raw(" ".repeat(gap.max(1))),
                    ];
                    if !shortcut.is_empty() {
                        spans.push(Span::styled(shortcut, Style::default().fg(Color::DarkGray)));
                    }
                    lines.push(Line::from(spans));
                }
            }
        }
        let mut title = format!(" {} ", self.title());
        if !self.page().query.is_empty() {
            title.push_str(&format!(
                "— \"{}\"{} ",
                self.page().query,
                if self.page().fuzzy { " (fuzzy)" } else { "" }
            ));
        }
        lines.push(Line::from(Span::styled(
            format!(
                "{} action{} · type to filter · ↑/↓ move · Enter run · Esc close",
                self.page().visible.len(),
                if self.page().visible.len() == 1 {
                    ""
                } else {
                    "s"
                }
            ),
            Style::default().fg(Color::DarkGray),
        )));
        let block = Block::default()
            .borders(Borders::ALL)
            .title(title)
            .border_style(Style::default().fg(Color::Cyan));
        f.render_widget(Paragraph::new(lines).block(block), rect);
    }
}

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

    fn sample() -> Vec<ActionMenuItem> {
        vec![
            ActionMenuItem::new(
                IssueAction::MoveTo {
                    column: "done".into(),
                },
                "Move to done",
                ActionGroup::Move,
            ),
            ActionMenuItem::new(IssueAction::OpenDetail, "Open detail", ActionGroup::Open)
                .shortcut("enter"),
            ActionMenuItem::new(IssueAction::Comment, "Comment", ActionGroup::Content)
                .shortcut("c"),
            ActionMenuItem::new(IssueAction::Delete, "Delete", ActionGroup::Destructive)
                .shortcut("d")
                .danger(true),
        ]
    }

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    #[test]
    fn starts_on_open_detail_and_skips_headers_for_movement() {
        let mut menu = ActionMenu::new(sample());
        assert_eq!(
            menu.selected_item().map(|item| item.action.clone()),
            Some(IssueAction::OpenDetail),
            "Open detail is preselected even though Move is drawn first"
        );
        menu.handle_key(key(KeyCode::Up));
        assert_eq!(
            menu.selected_item().map(|item| item.action.clone()),
            Some(IssueAction::MoveTo {
                column: "done".into()
            }),
            "Up reaches the first drawn item"
        );
        menu.handle_key(key(KeyCode::Down));
        let _ = menu.handle_key(key(KeyCode::Down));
        menu.handle_key(key(KeyCode::Down));
        menu.handle_key(key(KeyCode::Down));
        assert_eq!(
            menu.selected_item().map(|item| item.action.clone()),
            Some(IssueAction::Delete)
        );
        menu.handle_key(key(KeyCode::Down));
        assert_eq!(
            menu.selected_item().map(|item| item.action.clone()),
            Some(IssueAction::Delete),
            "the last item stays selected"
        );
    }

    #[test]
    fn typing_filters_literally_and_then_fuzzily() {
        let mut menu = ActionMenu::new(sample());
        for c in "open".chars() {
            menu.handle_key(key(KeyCode::Char(c)));
        }
        assert_eq!(menu.visible_len(), 1);
        assert!(!menu.is_fuzzy());
        assert_eq!(
            menu.selected_item().map(|item| item.action.clone()),
            Some(IssueAction::OpenDetail)
        );

        let mut menu = ActionMenu::new(sample());
        for c in "opndt".chars() {
            menu.handle_key(key(KeyCode::Char(c)));
        }
        assert!(menu.is_fuzzy(), "a bare subsequence falls back to fuzzy");
        assert_eq!(
            menu.selected_item().map(|item| item.action.clone()),
            Some(IssueAction::OpenDetail)
        );
    }

    #[test]
    fn backspace_restores_the_list_and_esc_dismisses() {
        let mut menu = ActionMenu::new(sample());
        for c in "dele".chars() {
            menu.handle_key(key(KeyCode::Char(c)));
        }
        assert_eq!(menu.visible_len(), 1);
        menu.handle_key(key(KeyCode::Backspace));
        assert_eq!(menu.visible_len(), 1, "'dele' still matches only Delete");
        menu.handle_key(key(KeyCode::Backspace));
        menu.handle_key(key(KeyCode::Backspace));
        menu.handle_key(key(KeyCode::Backspace));
        assert_eq!(menu.handle_key(key(KeyCode::Backspace)), MenuEvent::None);
        assert_eq!(menu.visible_len(), 4);
        assert_eq!(menu.handle_key(key(KeyCode::Esc)), MenuEvent::Dismissed);
    }

    #[test]
    fn submenu_pops_back_to_the_parent() {
        let mut menu = ActionMenu::new(sample());
        menu.push(
            "Relationships",
            vec![ActionMenuItem::new(
                IssueAction::RemoveRelationship { id: "r1".into() },
                "Remove #1",
                ActionGroup::Content,
            )],
        );
        assert_eq!(menu.title(), "Relationships");
        assert!(menu.pop());
        assert_eq!(menu.title(), "Actions");
        assert!(!menu.pop());
    }

    #[test]
    fn the_selected_item_survives_filtering_when_possible() {
        let mut menu = ActionMenu::new(sample());
        menu.handle_key(key(KeyCode::Down));
        menu.handle_key(key(KeyCode::Down));
        menu.handle_key(key(KeyCode::Char('d')));
        assert!(menu.selected_item().is_some());
    }

    #[test]
    fn enter_selects_the_highlighted_item() {
        let mut menu = ActionMenu::new(sample());
        // Open detail is preselected; Down moves to the next item.
        menu.handle_key(key(KeyCode::Down));
        assert_eq!(menu.handle_key(key(KeyCode::Enter)), MenuEvent::Selected(2));
    }
}