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
//! Filter modal widget (FR-014, T012 / WP02).
//!
//! The Tab-navigated filter editor: a `FilterModal` wraps a
//! [`StructuredFilter`](crate::search::StructuredFilter) in progress plus a
//! cursor over the field rows (mirrors `FormFocus` cycle in `src/ui/form.rs`
//! at 8–34). The widget is a **pure view + model**: it does not read keys at all.
//! [`App`](crate::app::App) routes them — `enter`/`l`/`right` open the focused row's
//! value picker (or the calendar on a date row), `ctrl+enter` commits, `esc` reverts
//! — and owns the transient picker. Criterion rows hold no typed text; a row's value
//! always comes from its picker. "Clear all" (FR-014) empties every criterion but
//! never fights the `/` text filter — the `/` query layer is reset by its own path.

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};

use crate::search::{FilterField, StructuredFilter};
use crate::ui::pickers::DropdownState;
use crate::views::divergence::ActiveViewMarker;
use crate::views::plan::ViewPlan;
use crate::views::registry::ViewId;

use super::modal::modal_rect;
use super::views::ViewFeedback;

/// Where an open criterion picker draws inside `area` (the filter modal's own rect)
/// and the rect of each visible option row, or `None` when there is nothing to show.
///
/// Mirrors [`crate::ui::triage::dropdown_layout`]: one clamp rule, so the list never
/// overflows the surface that owns it — a box too short or too narrow to hold a
/// title and one row simply does not draw.
pub fn picker_layout(area: Rect, state: &DropdownState) -> Option<(Rect, Vec<Rect>)> {
    let visible = state.visible_indices();
    if visible.is_empty() {
        return None;
    }
    let inner = Block::default().borders(Borders::ALL).inner(area);
    let widest = visible
        .iter()
        .map(|index| state.options[*index].label.chars().count() as u16 + 2)
        .max()
        .unwrap_or(0);
    let width = (widest + 4).clamp(6, inner.width.max(6));
    let height = (visible.len() as u16 + 2).min(inner.height.max(3));
    if height < 3 || inner.width == 0 {
        return None;
    }
    let rect = Rect::new(inner.x, inner.y, width, height);
    let rows = (0..visible.len() as u16)
        .take(height as usize - 2)
        .map(|row| Rect::new(rect.x, rect.y + 1 + row, rect.width, 1))
        .collect();
    Some((rect, rows))
}

/// The Tab-navigated structured-filter editor (T012).
///
/// WP05 adds one thing to it: the **active saved view** (T024). The modal holds
/// the marker — the stable id and the normalized plan that was applied — plus the
/// already-rendered indicator/feedback the app derived (T026). It is deliberately
/// *not* live filter state: `clear()` empties the criteria and leaves the marker
/// alone, because "the view the board is associated with" and "the criteria in
/// force" are two different facts (C-006), and only the second is editable here.
pub struct FilterModal {
    /// The StructuredFilter being edited.
    filter: StructuredFilter,
    /// Field row the cursor is on (Assignee → Label → Status → Priority).
    focus: FilterField,
    /// The saved view the live board is associated with, if any (T024).
    active: Option<ActiveViewMarker>,
    /// The rendered indicator and detail lines for `active`, refreshed by the app
    /// (T026). The widget owns no comparison and no diagnostics text.
    feedback: Option<ViewFeedback>,
}

impl Default for FilterModal {
    fn default() -> Self {
        Self::new()
    }
}

impl FilterModal {
    pub fn new() -> Self {
        Self {
            filter: StructuredFilter::default(),
            focus: FilterField::Assignee,
            active: None,
            feedback: None,
        }
    }

    /// Seed the modal with an existing filter (used when re-opening the modal
    /// for an already-applied filter).
    pub fn with_filter(filter: StructuredFilter) -> Self {
        Self {
            filter,
            focus: FilterField::Assignee,
            active: None,
            feedback: None,
        }
    }

    /// Install the active saved-view marker and its rendered feedback (T024).
    ///
    /// Informational: this changes what the modal *shows*, never the criteria it
    /// edits. The app calls it when the modal opens and after every live change
    /// while it is open, so the indicator cannot describe a state the board is no
    /// longer in.
    pub fn set_active(&mut self, active: Option<ActiveViewMarker>, feedback: Option<ViewFeedback>) {
        self.active = active;
        self.feedback = feedback;
    }

    /// The active saved-view marker, when the board is associated with one.
    pub fn active(&self) -> Option<&ActiveViewMarker> {
        self.active.as_ref()
    }

    /// The stable id of the active view — the identity, never the name (C-002).
    pub fn view_id(&self) -> Option<&ViewId> {
        self.active.as_ref().map(ActiveViewMarker::view_id)
    }

    /// The normalized plan that was applied when the marker was set.
    pub fn applied_plan(&self) -> Option<&ViewPlan> {
        self.active.as_ref().map(ActiveViewMarker::applied_plan)
    }

    /// Replace the rendered feedback (T026), which the app recomputes on every
    /// live change.
    pub fn set_feedback(&mut self, feedback: Option<ViewFeedback>) {
        self.feedback = feedback;
    }

    /// The indicator and detail lines currently rendered, when there are any.
    pub fn feedback(&self) -> Option<&ViewFeedback> {
        self.feedback.as_ref()
    }

    /// The one-line indicator, when the board is associated with a saved view.
    pub fn indicator_line(&self) -> Option<String> {
        self.feedback
            .as_ref()
            .map(|feedback| feedback.indicator.clone())
    }

    /// The rows the active-view feedback occupies above the criteria — one for
    /// the indicator, one blank, one per detail line (0 without a view).
    ///
    /// Public because the app places the criterion rows' click targets from the
    /// same arithmetic the widget draws with (D6): a hit region that ignored the
    /// feedback block would jump focus to the wrong criterion.
    pub fn header_height(&self) -> u16 {
        match &self.feedback {
            Some(feedback) => u16::try_from(feedback.lines.len())
                .unwrap_or(u16::MAX)
                .saturating_add(2),
            None => 0,
        }
    }

    /// Read the in-progress criteria for editing (App writes a picker's choice
    /// into it) and for the commit that closes the modal.
    pub fn active_filter(&self) -> &StructuredFilter {
        &self.filter
    }

    pub fn active_filter_mut(&mut self) -> &mut StructuredFilter {
        &mut self.filter
    }

    /// Clear/reset **all** criteria (FR-014). Never touches the `/` text
    /// filter layer (reset is a pure structured-filter op, mirrored by the
    /// query layer's own reset).
    ///
    /// The active-view marker is untouched: emptying the criteria is a live
    /// change, and a live change is exactly what the marker's divergence report
    /// exists to name (C-006). Clearing the marker here would hide the divergence
    /// the user just created.
    pub fn clear(&mut self) {
        self.filter = StructuredFilter::default();
        self.focus = FilterField::Assignee;
    }

    /// Move focus to the next criterion row (Tab).
    pub fn focus_next(&mut self) {
        self.focus = self.focus.next();
    }

    /// Move focus to the previous criterion row (Shift+Tab).
    pub fn focus_prev(&mut self) {
        self.focus = self.focus.prev();
    }

    /// Jump focus directly to a specific criterion row (a row click, D6) —
    /// the same focus state the Tab/arrow cycling produces, chosen directly.
    pub fn focus_field(&mut self, field: FilterField) {
        if FilterField::ALL.contains(&field) {
            self.focus = field;
        }
    }

    /// The currently-focused criterion row.
    pub fn focus(&self) -> FilterField {
        self.focus
    }

    /// Whether the focused criterion is a picker-only date field.
    pub fn is_date_focus(&self) -> bool {
        self.focus.is_date()
    }

    /// The focused criterion's value, or `""` when unset.
    pub fn focused_value(&self) -> String {
        self.focus.value(&self.filter).unwrap_or("").to_string()
    }

    /// Overwrite the focused date criterion (no-op when it isn't a date field).
    /// An empty value clears the criterion.
    pub fn set_focused_date(&mut self, value: &str) {
        if !self.focus.is_date() {
            return;
        }
        if value.is_empty() {
            self.focus.unset(&mut self.filter);
        } else {
            *self.focus.value_mut(&mut self.filter) = value.to_string();
        }
    }

    /// Render the filter modal: a bordered, centered box (via
    /// [`modal_rect`]) listing each criterion row (label + value)
    /// with the focused row highlighted; unset criteria show a placeholder.
    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::FilterModal,
        );
    }

    pub fn render_with_bindings(
        &self,
        f: &mut Frame,
        area: Rect,
        bindings: &crate::keybindings::EffectiveBindings,
        context: crate::keybindings::InputContext,
    ) {
        let rect = modal_rect(area);
        let mut rows: Vec<Line> = Vec::new();

        // The active saved view renders **above** the criteria (T024/T026): the
        // indicator is the same line the board's own row shows, and the lines
        // under it are the divergence/diagnostics the app computed. Nothing here
        // is edited by this modal.
        if let Some(feedback) = &self.feedback {
            rows.push(Line::from(Span::styled(
                feedback.indicator.clone(),
                Style::default()
                    .fg(Color::Green)
                    .add_modifier(Modifier::BOLD),
            )));
            for line in &feedback.lines {
                rows.push(Line::from(Span::styled(
                    line.clone(),
                    Style::default().fg(Color::DarkGray),
                )));
            }
            rows.push(Line::from(""));
        }

        for field in FilterField::ALL {
            let (label, value) = (field.label(), field.value(&self.filter));
            let is_focus = field == self.focus;
            let value_text = value.unwrap_or("(unset)");
            let style = if is_focus {
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(Color::White)
            };
            let label_style = if is_focus {
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(Color::DarkGray)
            };
            let prefix = if is_focus { "> " } else { "  " };
            rows.push(Line::from(vec![
                ratatui::text::Span::styled(format!("{prefix}{label}:"), label_style),
                ratatui::text::Span::styled(format!(" {value_text}"), style),
            ]));
        }

        // The separator is cosmetic: keep it only while the three hint lines below
        // still fit, so a criterion list that grew (WP06's `Epic` row) cannot push
        // the last hint — the one that says how to apply and close — out of the
        // modal's fixed 75%-height rect.
        let inner_h = rect.height.saturating_sub(2) as usize;
        if rows.len() + 3 < inner_h {
            rows.push(Line::from(""));
        }
        rows.push(Line::from(Span::styled(
            format!(
                "{}/{}: navigate",
                bindings.label(context, crate::keybindings::TuiAction::Next),
                bindings.label(context, crate::keybindings::TuiAction::Previous),
            ),
            Style::default().fg(Color::DarkGray),
        )));
        // Two lines rather than one: the modal is 75% of the terminal, so at 80
        // columns the interior is 58 wide and a single hint line carrying four
        // bindings would be silently truncated.
        rows.push(Line::from(Span::styled(
            format!(
                "{}: open \u{b7} {}: reset",
                bindings.label(context, crate::keybindings::TuiAction::OpenPicker),
                bindings.label(context, crate::keybindings::TuiAction::Reset),
            ),
            Style::default().fg(Color::DarkGray),
        )));
        // One wording for both exits: the modal applies ad-hoc, so closing keeps the
        // criteria and neither key is a discard.
        rows.push(Line::from(Span::styled(
            format!(
                "{} / {}: apply & close",
                bindings.label(context, crate::keybindings::TuiAction::Submit),
                bindings.label(context, crate::keybindings::TuiAction::Cancel),
            ),
            Style::default().fg(Color::DarkGray),
        )));

        let block = Block::default()
            .borders(Borders::ALL)
            .title(" Filter ")
            .style(Style::default().fg(Color::Cyan));
        let para = Paragraph::new(rows).block(block).style(Style::default());
        f.render_widget(Clear, rect);
        f.render_widget(para, rect);
    }
}

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

    fn smoke(w: u16, h: u16, title_focus: bool) {
        let backend = TestBackend::new(w, h);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal
            .draw(|f| {
                let area = f.area();
                let mut modal = FilterModal::new();
                if title_focus {
                    modal.focus_next();
                }
                modal.render(f, area);
            })
            .unwrap();
    }

    #[test]
    fn renders_at_120x40() {
        smoke(120, 40, false);
    }

    #[test]
    fn renders_at_80x24() {
        smoke(80, 24, false);
    }

    #[test]
    fn renders_at_tiny_20x5() {
        smoke(20, 5, true);
    }

    fn buffer_text(w: u16, h: u16) -> String {
        let backend = TestBackend::new(w, h);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal
            .draw(|f| {
                let modal = FilterModal::new();
                modal.render(f, f.area());
            })
            .unwrap();
        let buffer = terminal.backend().buffer();
        let mut text = String::new();
        for y in 0..h {
            for x in 0..w {
                for ch in buffer[(x, y)].symbol().chars() {
                    text.push(ch);
                }
            }
            text.push('\n');
        }
        text
    }

    #[test]
    fn footer_hint_present_at_normal_size() {
        let text = buffer_text(80, 24);
        assert!(
            text.contains("Tab / Down/Shift+Tab / Up: navigate"),
            "footer must advertise field navigation, got:\n{text}"
        );
        assert!(
            text.contains("F2 / Enter / l / Right: open"),
            "footer must advertise the row picker on enter/l/right, got:\n{text}"
        );
        assert!(
            text.contains("r / Shift+R: reset"),
            "footer must advertise the reset key, got:\n{text}"
        );
        assert!(
            text.contains("a / Esc: apply & close"),
            "footer must advertise that closing applies the filter, got:\n{text}"
        );
    }

    #[test]
    fn footer_render_does_not_panic_on_tiny_terminal() {
        let text = buffer_text(20, 5);
        assert_ne!(text, "");
    }

    #[test]
    fn focus_cycles_forward() {
        let mut modal = FilterModal::new();
        assert_eq!(modal.focus(), FilterField::Assignee);
        modal.focus_next();
        assert_eq!(modal.focus(), FilterField::Label);
        modal.focus_next();
        modal.focus_next();
        assert_eq!(modal.focus(), FilterField::Priority);
        modal.focus_next();
        assert_eq!(modal.focus(), FilterField::Cycle);
    }

    #[test]
    fn focus_cycles_backward() {
        let mut modal = FilterModal::new();
        // The backward wrap lands on the **last** row, whatever that is — and the
        // last row has changed four times. `Parent` was appended as the tenth (T024
        // step 2), `Category` as the eleventh (WP08 T034 step 2), `Project` as the
        // twelfth (WP06 T026) and `Epic` as the thirteenth (WP06 T028), all appended
        // rather than interleaved. This is the one place the appending decision is
        // visible, and it is visible on purpose: a user pressing Up from the first
        // row should reach the last row, not a row chosen by history.
        modal.focus_prev();
        assert_eq!(modal.focus(), FilterField::Epic);
        modal.focus_prev();
        assert_eq!(modal.focus(), FilterField::Project);
        modal.focus_prev();
        assert_eq!(modal.focus(), FilterField::Category);
        modal.focus_prev();
        assert_eq!(modal.focus(), FilterField::Parent);
        modal.focus_prev();
        assert_eq!(modal.focus(), FilterField::DueDate);
        modal.focus_prev();
        assert_eq!(modal.focus(), FilterField::StartDate);
    }

    #[test]
    fn clear_resets_all_criteria_and_focus() {
        let mut modal = FilterModal::with_filter(StructuredFilter {
            assignee: Some("alice".to_string()),
            label: Some("urgent".to_string()),
            status: Some("todo".to_string()),
            priority: Some("high".to_string()),
            cycle: None,
            milestone: None,
            reviewer: None,
            start_date: None,
            due_date: None,
            overdue: None,
            parent: None,
            category: None,
            scope: None,
            archived: None,
            project: None,
            epic: None,
        });
        modal.clear();
        assert_eq!(modal.active_filter(), &StructuredFilter::default());
        assert_eq!(modal.focus(), FilterField::Assignee);
    }
}