tix-tracker 0.6.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
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};

use crate::assignee::assignee_display;
use crate::model::Priority;

use super::board::Card;

pub fn priority_glyph(priority: &Priority) -> &'static str {
    match priority {
        Priority::High => "!",
        Priority::Other(s) if s.eq_ignore_ascii_case("urgent") => "!!",
        _ => "",
    }
}

pub fn priority_style(priority: &Priority) -> Style {
    match priority {
        Priority::High => Style::default().fg(Color::Red),
        Priority::Other(s) if s.eq_ignore_ascii_case("urgent") => {
            Style::default().fg(Color::Red).add_modifier(Modifier::BOLD)
        }
        Priority::Low => Style::default().fg(Color::DarkGray),
        _ => Style::default(),
    }
}

/// Single-line card render (title wrapping disabled), truncated to `width`.
/// Kept for callers and tests that want today's one-line behavior.
pub fn card_line(card: &Card, width: usize) -> Line<'static> {
    let mut lines = card_lines(card, width, false, 1);
    lines.remove(0)
}

/// The styled word tokens making up a card's rendered content: `#N`, the
/// title words, priority glyph, assignee, and up to three labels. Wrapping and
/// truncation operate on this token stream so suffix segments (assignee,
/// labels) flow onto continuation lines instead of overflowing the column.
/// The styled tokens one card's first line is made of.
///
/// `pub` so a test can assert the **marker text** rather than a screenshot of it.
/// A board rendering test that only captures the whole screen cannot say *why* it
/// passed, and a marker with the wrong contents still renders a screen.
pub fn card_tokens(card: &Card) -> Vec<(String, Style)> {
    let mut tokens = Vec::new();
    tokens.push((
        format!("#{}", card.number),
        Style::default().fg(Color::Cyan),
    ));
    // Related-count marker (tix #1513), immediately after the number so a long
    // title can never wrap it off the card — the same reason the blocked marker is
    // pushed before the suffix tokens. A count, not the entries: the card is one or
    // two lines wide, and the list itself belongs to the detail pane. Magenta
    // matches the detail pane's `related:` block, so one color means one concept on
    // both surfaces.
    if card.related > 0 {
        tokens.push((
            format!("[↔ {}]", card.related),
            Style::default().fg(Color::Magenta),
        ));
    }
    tokens.extend(
        card.title
            .split_whitespace()
            .map(|w| (w.to_string(), Style::default())),
    );
    let glyph = priority_glyph(&card.priority);
    if !glyph.is_empty() {
        tokens.push((glyph.to_string(), priority_style(&card.priority)));
    }
    if let Some(a) = &card.assignee {
        let name = assignee_display(a);
        if !name.is_empty() {
            tokens.push((name, Style::default().fg(Color::Green)));
        }
    }
    // Blocked marker, immediately after the number so it is visible however the
    // title wraps. A glyph rather than the reason: the card is one or two lines
    // wide, and the full reason belongs in the detail view and the move warning.
    // `[~]` matches the board's existing bracketed-marker language (`[overdue]`,
    // `[label]`).
    if card.blocked.is_some() {
        tokens.push(("[~]".to_string(), Style::default().fg(Color::Red)));
    }
    // Child-count marker, in the same bracketed language and next to the blocked
    // marker, so a parent is identifiable on the board without opening it. A
    // *count* and a *rollup* rather than a word: the card is one or two lines wide.
    // A leaf has no marker at all, so the column of cards stays scannable.
    if let Some(children) = &card.children {
        tokens.push((format!("[{children}]"), Style::default().fg(Color::Cyan)));
    }
    // Archived marker (issue #1492), in the same bracketed language as `[~]` and
    // `[N]`. Dim, because an archived issue is history rather than work — it is
    // shown because the toggle asked for it, and it should not compete with the
    // active cards for attention.
    if card.archived {
        tokens.push((
            "[archived]".to_string(),
            Style::default().fg(Color::DarkGray),
        ));
    }
    for label in card.labels.iter().take(3) {
        tokens.push((format!("[{label}]"), Style::default().fg(Color::Yellow)));
    }
    // WP05: the category chip (T022/T024). Placed next to the other bracketed
    // markers so it reads in the same visual language as `[overdue]` and `[~]`.
    tokens.push(category_token(
        card.category.as_deref(),
        card.category_color,
    ));
    if card
        .due_date
        .as_deref()
        .is_some_and(|due| due < crate::model::today().as_str())
        // WP05: `card.done` is the **service's** completion decision (C-004). This
        // compared `card.status != "done"` — a literal column name, in a file whose
        // sibling field already had the right answer. On a board whose completion
        // column is `shipped`, a completed issue with a past due date was marked
        // `[overdue]`.
        && !card.done
    {
        tokens.push(("[overdue]".to_string(), Style::default().fg(Color::Red)));
    }
    tokens
}

/// The category chip: a bracketed label, tinted by the category's color hint.
///
/// WP05 T024. Added because the **board card and the detail view both** need
/// "category label, optionally tinted", and rendering it twice is how the two drift
/// into spelling one category two ways — the failure the parity contract names.
///
/// **The label carries the meaning; the color only tints it** (FR-004, research R6).
/// A board or terminal with no color still shows the category, because the text is
/// unconditional and `hint` merely selects a foreground. That is the whole reason
/// this is a function and not a style: a caller cannot forget the label by forgetting
/// the color.
///
/// **No policy and no resolution.** It is handed a label and a hint and renders them;
/// it does not ask what a column means, and it cannot be made to disagree with the
/// service by editing this file. `None` renders `(unmapped)`, which is the renderers'
/// spelling for a column the board does not configure — a statement about the file,
/// not a transition-policy default.
pub fn category_token(
    label: Option<&str>,
    hint: Option<crate::workflow::ColorHint>,
) -> (String, Style) {
    let text = format!("[{}]", label.unwrap_or("unmapped"));
    let style = match hint {
        Some(crate::workflow::ColorHint::Dim) => Style::default().fg(Color::DarkGray),
        Some(crate::workflow::ColorHint::Accent) => Style::default().fg(Color::Cyan),
        Some(crate::workflow::ColorHint::Warn) => Style::default().fg(Color::Yellow),
        Some(crate::workflow::ColorHint::Ok) => Style::default().fg(Color::Green),
        Some(crate::workflow::ColorHint::Muted) => Style::default().fg(Color::Gray),
        // No hint: the label is still rendered, in the default foreground. This arm
        // is the no-color case T022 step 3 and T025 step 5 pin.
        None => Style::default(),
    };
    (text, style)
}

/// Render a card as up to `max_lines` lines at `width` columns. With `wrap`
/// on, tokens are greedily wrapped onto the next line when they no longer fit;
/// the whole card body is clamped to `max_lines` and any surplus is clipped.
/// With `wrap` off the card is a single line truncated to `width`. Widths are
/// measured per Unicode column (CJK chars count 2) so wrapped lines never poke
/// through the column border.
pub fn card_lines(card: &Card, width: usize, wrap: bool, max_lines: usize) -> Vec<Line<'static>> {
    let tokens = card_tokens(card);
    let mut lines = if wrap {
        greedy_wrap(&tokens, width)
    } else {
        vec![tokens]
    };
    if lines.len() > max_lines {
        lines.truncate(max_lines);
    }
    let mut rendered: Vec<Line<'static>> = lines
        .into_iter()
        .map(|line_tokens| Line::from(truncate_tokens(&line_tokens, width)))
        .collect();
    indent_sub_issue(card, &mut rendered);
    rendered
}

/// Prefix a sub-issue card's lines with the tree marker (tix #1399).
///
/// A `depth == 0` card's lines are left untouched. A `depth == 1` card gets `└ ` on
/// its first line and two spaces on every continuation line, so the whole card reads
/// as hanging off the parent above it.
///
/// The marker is **added**, never carved out of the wrapped body: the tokens are
/// still wrapped at the same `width`, so the line count is exactly what it was
/// before the indent — and therefore exactly what [`card_line_count`] reports. That
/// is what keeps the pointer hit-test aligned with the drawn rows. The leading two
/// cells are clipped by the column, a cost paid only on a card that is already
/// marked as subordinate.
fn indent_sub_issue(card: &Card, lines: &mut [Line<'static>]) {
    if card.depth == 0 {
        return;
    }
    for (index, line) in lines.iter_mut().enumerate() {
        let marker = if index == 0 { "└ " } else { "  " };
        let mut spans = vec![Span::styled(marker, Style::default().fg(Color::DarkGray))];
        spans.append(&mut line.spans);
        *line = Line::from(spans);
    }
}

/// The number of rows `card_lines` renders for `card` at `width` — the exact
/// index a `List` item occupies. Computed with the same wrap and title-line
/// clamping so pointer hit-testing can never drift from what is drawn (D3);
/// always at least 1 and bounded by `max_lines`.
pub fn card_line_count(card: &Card, width: usize, wrap: bool, max_lines: usize) -> u16 {
    let count = if wrap {
        greedy_wrap(&card_tokens(card), width).len()
    } else {
        1
    };
    let count = count.min(max_lines).max(1);
    u16::try_from(count).unwrap_or(u16::MAX)
}

fn greedy_wrap(tokens: &[(String, Style)], width: usize) -> Vec<Vec<(String, Style)>> {
    let mut lines: Vec<Vec<(String, Style)>> = Vec::new();
    let mut cur: Vec<(String, Style)> = Vec::new();
    let mut cur_width = 0usize;
    for (word, style) in tokens {
        let w = Span::raw(word).width();
        if !cur.is_empty() && cur_width + 1 + w > width {
            lines.push(std::mem::take(&mut cur));
            cur_width = 0;
        }
        cur.push((word.clone(), *style));
        cur_width += if cur.len() == 1 { w } else { w + 1 };
    }
    if !cur.is_empty() {
        lines.push(cur);
    }
    if lines.is_empty() {
        lines.push(Vec::new());
    }
    lines
}

fn truncate_tokens(tokens: &[(String, Style)], width: usize) -> Vec<Span<'static>> {
    let mut spans: Vec<Span<'static>> = Vec::new();
    let mut used = 0usize;
    let mut first = true;
    for (word, style) in tokens {
        let w = Span::raw(word).width();
        let sep = if first { 0 } else { 1 };
        first = false;
        if used + sep + w <= width {
            if sep == 1 {
                spans.push(Span::raw(" "));
                used += 1;
            }
            spans.push(Span::styled(word.clone(), *style));
            used += w;
        } else if used < width {
            let clipped = clip_to_width(word, width - used);
            if !clipped.is_empty() {
                spans.push(Span::styled(clipped, *style));
            }
            break;
        } else {
            break;
        }
    }
    spans
}

fn clip_to_width(word: &str, target: usize) -> String {
    let mut acc = String::new();
    for ch in word.chars() {
        let cand = format!("{acc}{ch}");
        if Span::raw(&cand).width() <= target {
            acc.push(ch);
        } else {
            break;
        }
    }
    acc
}

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

    fn card(priority: Priority) -> Card {
        Card {
            number: 1,
            title: "Test".into(),
            priority,
            labels: vec![],
            assignee: None,
            filename: "test.md".into(),
            commit: None,
            created: "2026-01-01".into(),
            due_date: None,
            status: "todo".into(),
            category: None,
            category_color: None,
            done: false,
            cycle: None,
            milestone: None,
            blocked: None,
            children: None,
            parent: None,
            depth: 0,
            archived: false,
            related: 0,
        }
    }

    #[test]
    fn glyph_high_is_bang() {
        assert_eq!(priority_glyph(&Priority::High), "!");
    }

    #[test]
    fn glyph_urgent_is_double_bang() {
        assert_eq!(priority_glyph(&Priority::Other("urgent".into())), "!!");
    }

    #[test]
    fn glyph_medium_is_empty() {
        assert_eq!(priority_glyph(&Priority::Medium), "");
    }

    #[test]
    fn card_line_renders_number_and_title() {
        let c = card(Priority::Medium);
        let line = card_line(&c, 40);
        let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.contains("#1"));
        assert!(text.contains("Test"));
    }

    #[test]
    fn card_line_high_priority_shows_glyph() {
        let c = card(Priority::High);
        let line = card_line(&c, 40);
        let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.contains("!"));
    }

    #[test]
    fn card_line_assignee_shows_at_prefix() {
        let c = Card {
            assignee: Some("alice".into()),
            ..card(Priority::Medium)
        };
        let line = card_line(&c, 40);
        let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.contains("@alice"));
    }

    #[test]
    fn card_line_identity_shows_name_only() {
        let c = Card {
            assignee: Some("Herbert Maschke <thyseus@pm.me>".into()),
            ..card(Priority::Medium)
        };
        let line = card_line(&c, 40);
        let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.contains("Herbert Maschke"));

        assert!(
            !text.contains("thyseus@pm.me"),
            "identity email must not leak into the board line: {text:?}"
        );
    }

    #[test]
    fn card_line_shows_first_three_labels() {
        let c = Card {
            labels: vec!["a".into(), "b".into(), "c".into(), "d".into()],
            ..card(Priority::Medium)
        };
        let line = card_line(&c, 40);
        let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.contains("[a]"));
        assert!(text.contains("[b]"));
        assert!(text.contains("[c]"));
        assert!(!text.contains("[d]"));
    }

    #[test]
    fn card_line_shows_overdue_tag_for_open_past_due() {
        let c = Card {
            due_date: Some("2000-01-01".into()),
            status: "todo".into(),
            ..card(Priority::Medium)
        };
        let line = card_line(&c, 80);
        let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.contains("[overdue]"));
    }

    /// tix #1513 T008: a card with `related_issues` carries a count marker, right
    /// after `#num`; a card with none carries no marker at all.
    #[test]
    fn card_shows_a_related_count_right_after_the_number() {
        let none = card_tokens(&card(Priority::Medium));
        assert!(
            none.iter().all(|(text, _)| !text.starts_with("[↔")),
            "a card with no related_issues has no marker: {none:?}"
        );

        let c = Card {
            related: 3,
            ..card(Priority::Medium)
        };
        let tokens = card_tokens(&c);
        assert_eq!(tokens[0].0, "#1", "the number stays the first token");
        assert_eq!(
            tokens[1].0, "[↔ 3]",
            "the related count sits immediately after the number, so title wrapping \
             cannot hide it: {tokens:?}"
        );
        assert_eq!(
            tokens[1].1.fg,
            Some(Color::Magenta),
            "the marker uses the detail pane's related accent"
        );
    }

    fn long_title() -> Card {
        Card {
            title: "very long title that definitely exceeds a narrow column width".into(),
            ..card(Priority::Medium)
        }
    }

    #[test]
    fn no_wrap_is_single_truncated_line() {
        let c = long_title();
        let lines = card_lines(&c, 20, false, 3);
        assert_eq!(lines.len(), 1, "wrap off always yields one line");
        let text: String = lines[0].spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.len() <= 20, "line is truncated to width: {text:?}");
    }

    #[test]
    fn wrap_produces_multiple_lines() {
        let c = long_title();
        let lines = card_lines(&c, 20, true, 10);
        assert!(lines.len() > 1, "long title wraps across lines");
        for line in &lines {
            let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
            let width = line.width();
            assert!(width <= 20, "wrapped line fits width: {text:?} ({width})");
        }
        let joined: String = lines
            .iter()
            .flat_map(|l| l.spans.iter().map(|s| s.content.as_ref()))
            .collect();
        assert!(joined.contains("long") && joined.contains("column"));
    }

    #[test]
    fn wrapped_card_clamped_to_line_limit() {
        let c = long_title();
        let lines = card_lines(&c, 15, true, 3);
        assert!(lines.len() <= 3, "clamped at max_lines");
        let some_lines = card_lines(&c, 15, true, 5);
        assert!(
            some_lines.len() > lines.len(),
            "clamping removes surplus lines"
        );
    }

    #[test]
    fn overlong_single_token_is_truncated() {
        let c = Card {
            title: "supercalifragilisticexpialidocious".into(),
            ..card(Priority::Medium)
        };
        let lines = card_lines(&c, 10, true, 3);
        let first = &lines[0];
        let text: String = first.spans.iter().map(|s| s.content.as_ref()).collect();
        let width = first.width();
        assert!(width <= 10, "token clipped to width: {text:?} ({width})");
    }

    #[test]
    fn cjk_widths_count_two_columns_each() {
        let c = Card {
            title: "思出 头辞失 音州".into(),
            ..card(Priority::Medium)
        };
        // Each CJK char is 2 columns: `#1` (2) + "思出" (4) + space = 7 fits
        // width 8; the following 6-column word must wrap to the next line.
        let lines = card_lines(&c, 8, true, 5);
        assert!(lines.len() > 1, "CJK title wraps on the 2-column boundary");
        for line in &lines {
            assert!(
                line.width() <= 8,
                "CJK line fits width: {line:?} ({})",
                line.width()
            );
        }
        let joined: String = lines
            .iter()
            .flat_map(|l| l.spans.iter().map(|s| s.content.as_ref()))
            .collect();
        assert!(
            joined.contains("思出头辞失音州"),
            "no characters lost: {joined}"
        );
    }
}