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
use crate::app::{App, SortColumn, SortOrder};
use crate::models::{GitlabMrState, MergeabilityStatus, MrStatus, PipelineState};
use crate::ui::inspector::create_chip_span;
use ratatui::{
layout::{Constraint, Rect},
style::{Color, Modifier, Style, Stylize},
text::{Line, Span},
widgets::{Cell, Row, Table},
};
/// Fixed width (in chars) for all state badges, padding included.
/// "CI STILL RUNNING" is 16 chars — add 2 chars of padding (1 each side) → 18.
pub const BADGE_WIDTH: usize = 18;
/// Centers `text` inside a field of exactly `BADGE_WIDTH` characters.
/// Excess space is distributed evenly left and right (left-biased on odd remainder).
pub fn badge_label(text: &str) -> String {
// Use Rust's built-in centering formatter.
format!("{:^width$}", text, width = BADGE_WIDTH)
}
/// Returns a styled badge cell for the GitLab MR state.
///
/// For open MRs, `tick` (the current `time_left` value) drives a three-phase animation:
/// - tick % 3 == 0 → "OPEN" base badge (green)
/// - tick % 3 == 1 → mergeability badge (colour varies)
/// - tick % 3 == 2 → CI pipeline badge when the latest pipeline is running or pending,
/// otherwise falls back to the mergeability badge
///
/// All badges share the same `BADGE_WIDTH` so the column never shifts.
fn state_badge(
state: &GitlabMrState,
mergeability: &MergeabilityStatus,
pipelines: &[crate::models::Pipeline],
tick: u64,
) -> Cell<'static> {
// For non-open states the badge is static — mergeability is not meaningful.
if *state != GitlabMrState::Opened {
let (text, fg, bg) = match state {
GitlabMrState::Merged => ("MERGED", Color::Black, Color::Magenta),
GitlabMrState::Closed => ("CLOSED", Color::Black, Color::Red),
GitlabMrState::Opened => unreachable!(),
};
return Cell::from(Line::from(Span::styled(
badge_label(text),
Style::default().fg(fg).bg(bg).add_modifier(Modifier::BOLD),
)));
}
// Detect whether the latest pipeline is actively running or pending.
let ci_active = pipelines
.first()
.is_some_and(|p| matches!(p.status, PipelineState::Running | PipelineState::Pending));
// tick % 3 == 0: always show the base "OPEN" badge.
if tick.is_multiple_of(3) {
return Cell::from(Line::from(Span::styled(
badge_label("OPEN"),
Style::default()
.fg(Color::Black)
.bg(Color::Green)
.add_modifier(Modifier::BOLD),
)));
}
// tick % 3 == 2 and CI is running: show animated CI badge.
if tick % 3 == 2 && ci_active {
// Alternate between two spinner frames to create a pulse effect.
let label = if tick % 6 < 3 {
"CI RUNNING"
} else {
"CI PENDING"
};
return Cell::from(Line::from(Span::styled(
badge_label(label),
Style::default()
.fg(Color::Black)
.bg(Color::Rgb(180, 120, 0))
.add_modifier(Modifier::BOLD),
)));
}
// tick % 3 == 1, or tick % 3 == 2 with no active CI: show the mergeability badge.
let (text, fg, bg) = match mergeability {
MergeabilityStatus::Mergeable => ("MERGEABLE", Color::Black, Color::LightGreen),
MergeabilityStatus::Conflict => ("CONFLICT", Color::White, Color::Red),
MergeabilityStatus::NeedsRebase => ("REBASE", Color::Black, Color::Yellow),
MergeabilityStatus::NotOpen => ("CLOSED", Color::Black, Color::Red),
MergeabilityStatus::Draft => ("DRAFT", Color::White, Color::Rgb(80, 80, 80)),
MergeabilityStatus::DiscussionsNotResolved => {
("DISCUSSIONS", Color::Black, Color::LightMagenta)
}
MergeabilityStatus::CiMustPass => ("CI MUST PASS", Color::Black, Color::LightYellow),
MergeabilityStatus::CiStillRunning => ("CI STILL RUNNING", Color::Black, Color::Yellow),
MergeabilityStatus::NotApproved => ("NOT APPROVED", Color::Black, Color::LightRed),
MergeabilityStatus::RequestedChanges => ("REQUESTED CHANGES", Color::White, Color::Red),
MergeabilityStatus::Unknown => ("OPEN", Color::Black, Color::Green),
};
Cell::from(Line::from(Span::styled(
badge_label(text),
Style::default().fg(fg).bg(bg).add_modifier(Modifier::BOLD),
)))
}
pub fn render_table(app: &App, area: Rect) -> Table<'static> {
let _ = area; // Reserved for future use (e.g. dynamic column width)
// Resolve column visibility via the inventory-registered ColumnDef ids.
// This replaces the old fixed-field `VisibleColumns` struct accesses.
let col = |id: &str| app.config.visible_columns.is_visible(id);
// Build the header dynamically based on enabled optional columns.
let mut header_cells = vec![
Cell::from("MR ID"),
Cell::from("Title / API Status"),
Cell::from("Status").bold(),
];
if col("activity") {
header_cells.push(Cell::from("Activity").bold());
}
if col("target_branch") {
header_cells.push(Cell::from("Target").bold());
}
if col("labels") {
header_cells.push(Cell::from("Labels").bold());
}
if col("milestone") {
header_cells.push(Cell::from("Milestone").bold());
}
if col("notes") {
header_cells.push(Cell::from("Notes").bold());
}
if col("diff_stats") {
header_cells.push(Cell::from("Complexity").bold());
}
if col("tracker_ticket") {
header_cells.push(Cell::from("Tracker").bold());
}
for b in &app.branches {
header_cells.push(Cell::from(b.clone()).bold());
}
let header = Row::new(header_cells).bottom_margin(1).underlined();
let rows: Vec<Row> = app
.visible_mrs()
.map(|mr| {
// Always compute the label cell — used only when the column is enabled.
let filtered_labels: Vec<&String> = mr
.labels
.iter()
.filter(|l| app.config.is_table_label(l))
.collect();
let label_cell = if filtered_labels.is_empty() {
Cell::from("-").dark_gray()
} else {
let mut spans = Vec::new();
for label in filtered_labels {
let gitlab_color = app
.config
.gitlab_label_colors
.get(&label.to_lowercase())
.map(|s| s.as_str());
spans.push(create_chip_span(label, &app.config, gitlab_color));
spans.push(ratatui::text::Span::raw(" "));
}
Cell::from(Line::from(spans))
};
// Whether this row should receive the "recently updated" highlight.
// Cells must be individually coloured because a Row-level bg is overridden
// by any Cell that sets its own fg/bg style.
let highlight = mr.recently_updated && app.update_highlight_ticks > 0;
/// Applies the update-highlight background to a cell when active.
/// The foreground is left untouched so each cell keeps its own colour.
fn maybe_highlight(cell: Cell<'static>, highlight: bool) -> Cell<'static> {
if highlight {
cell.bg(Color::Rgb(0, 90, 40))
} else {
cell
}
}
// Build the title cell — prepend a coloured flag chevron for flagged MRs.
let title_cell = if mr.flagged {
let title_color = match mr.status {
MrStatus::Error => Color::Red,
_ => Color::White,
};
Cell::from(Line::from(vec![
Span::styled(
"★ ",
Style::default()
.fg(Color::Yellow)
.add_modifier(Modifier::BOLD),
),
Span::styled(mr.title.clone(), Style::default().fg(title_color)),
]))
} else {
Cell::from(mr.title.clone()).fg(match mr.status {
MrStatus::Error => Color::Red,
_ => Color::White,
})
};
// Fixed columns — always present.
let mut cells = vec![
maybe_highlight(Cell::from(format!("!{}", mr.id)), highlight),
maybe_highlight(title_cell, highlight),
maybe_highlight(
state_badge(&mr.state, &mr.mergeability, &mr.pipelines, app.time_left),
highlight,
),
];
// Optional columns — inserted only when enabled in config.
if col("activity") {
let (icon, color) = app.config.activity_badge(mr.updated_at.as_deref());
cells.push(maybe_highlight(Cell::from(icon).fg(color), highlight));
}
if col("target_branch") {
cells.push(maybe_highlight(
Cell::from(mr.target_branch.clone()).fg(Color::LightBlue),
highlight,
));
}
if col("labels") {
cells.push(maybe_highlight(label_cell, highlight));
}
if col("milestone") {
cells.push(maybe_highlight(
Cell::from(mr.milestone.clone()).fg(Color::Cyan),
highlight,
));
}
if col("notes") {
let (notes_text, notes_color) = if mr.user_notes_count == 0 {
("✔ 0".to_string(), Color::DarkGray)
} else {
(format!("💬 {}", mr.user_notes_count), Color::Yellow)
};
cells.push(maybe_highlight(
Cell::from(notes_text).fg(notes_color),
highlight,
));
}
// Optional complexity column — shows a fixed-width coloured chip badge
// matching the side-panel style. All labels are uppercased and padded to
// the width of the longest one ("COMPLEX") so every chip is the same size.
// Emoji glyphs occupy 2 terminal columns, so padding is computed manually:
// 🟢 EASY → 2 + 5 = 7 → 3 trailing spaces to reach 10
// 🟡 MEDIUM → 2 + 7 = 9 → 1 trailing space to reach 10
// 🔴 COMPLEX → 2 + 8 = 10 → no extra padding needed
if col("diff_stats") {
let complexity_cell = match &mr.diff_stats {
Some(stats) => {
let score = stats.difficulty(&app.config.complexity_profile);
let (label, fg, bg) = if score < 0.33 {
("🟢 EASY ", Color::Black, Color::Green)
} else if score < 0.66 {
("🟡 MEDIUM ", Color::Black, Color::Yellow)
} else {
("🔴 COMPLEX", Color::White, Color::Red)
};
Cell::from(Line::from(vec![Span::styled(
format!(" {} ", label),
Style::default().fg(fg).bg(bg).add_modifier(Modifier::BOLD),
)]))
}
None => Cell::from("—").fg(Color::DarkGray),
};
cells.push(maybe_highlight(complexity_cell, highlight));
}
// Optional tracker ticket column — visible when a provider is configured.
if col("tracker_ticket") {
let ticket_cell = match &mr.linked_ticket {
Some(t) => {
// Format time tracking as "Xh Ym" — reused from inspector logic.
let fmt_duration = |secs: u32| -> String {
if secs == 0 {
return "—".to_string();
}
let h = secs / 3600;
let m = (secs % 3600) / 60;
match (h, m) {
(0, m) => format!("{}m", m),
(h, 0) => format!("{}h", h),
(h, m) => format!("{}h {}m", h, m),
}
};
let has_tracking = t.time_estimate.map(|v| v > 0).unwrap_or(false)
|| t.time_spent.map(|v| v > 0).unwrap_or(false);
if has_tracking {
let spent = t
.time_spent
.map(fmt_duration)
.unwrap_or_else(|| "—".to_string());
let estimate = t
.time_estimate
.map(fmt_duration)
.unwrap_or_else(|| "—".to_string());
// Colour the tracking ratio: green < 80 %, yellow 80–100 %, red over budget.
let ratio_color = match (t.time_estimate, t.time_spent) {
(Some(est), Some(sp)) if est > 0 => {
let ratio = sp as f32 / est as f32;
if ratio >= 1.0 {
Color::Red
} else if ratio >= 0.8 {
Color::Yellow
} else {
Color::Green
}
}
_ => Color::DarkGray,
};
let spans = vec![
Span::styled(
format!("#{} {} ", t.id, t.status),
Style::default()
.fg(Color::LightMagenta)
.add_modifier(Modifier::BOLD),
),
Span::styled(
format!("{}/{}", spent, estimate),
Style::default().fg(ratio_color),
),
];
Cell::from(Line::from(spans))
} else {
let text = format!("#{} {}", t.id, t.status);
Cell::from(text).fg(Color::LightMagenta)
}
}
None => Cell::from("—").fg(Color::DarkGray),
};
cells.push(maybe_highlight(ticket_cell, highlight));
}
for b in &app.branches {
let cell = match &mr.status {
MrStatus::Loading => Cell::from("⏳ LOADING...").yellow(),
MrStatus::Error => Cell::from("❌ FAILED").red(),
MrStatus::MergedIn(set) => {
if set.contains(b) {
Cell::from("🟢 PRESENT").green()
} else {
Cell::from("🔴 ABSENT").red()
}
}
};
cells.push(maybe_highlight(cell, highlight));
}
Row::new(cells)
})
.collect();
// Build constraints in lockstep with the header/row cells.
// State badge column width must match BADGE_WIDTH exactly so the text is centred.
let mut constraints = vec![
Constraint::Length(8), // ID
Constraint::Fill(3), // Title
Constraint::Length(BADGE_WIDTH as u16 + 2), // State badge
];
if col("activity") {
constraints.push(Constraint::Length(12)); // Activity badge
}
if col("target_branch") {
constraints.push(Constraint::Fill(2)); // Target branch
}
if col("labels") {
constraints.push(Constraint::Fill(2)); // Labels
}
if col("milestone") {
// Milestone gets a smaller share when the tracker column is also visible,
// to give more room to the ticket subject which is typically longer.
let milestone_fill = if col("tracker_ticket") { 1 } else { 2 };
constraints.push(Constraint::Fill(milestone_fill)); // Milestone
}
if col("notes") {
constraints.push(Constraint::Length(10)); // Notes badge
}
if col("diff_stats") {
constraints.push(Constraint::Length(14)); // Complexity chip badge (e.g. " 🔴 Complex ")
}
if col("tracker_ticket") {
constraints.push(Constraint::Fill(2)); // Tracker ticket
}
for _ in &app.branches {
constraints.push(Constraint::Fill(1));
}
let mins = app.time_left / 60;
let secs = app.time_left % 60;
let sort_label = match app.sort_column {
SortColumn::UpdatedAt => "Updated ↕",
SortColumn::Id => "ID ↕",
SortColumn::Milestone => "Milestone ↕",
SortColumn::Title => "Title ↕",
};
let order_label = match app.sort_order {
SortOrder::Ascending => "↑",
SortOrder::Descending => "↓",
};
let filter_label = app.active_filter.label(&app.filter_defs);
// Show "X/Y MRs" when a filter is active, plain "Y MRs" otherwise.
let total = app.mrs.len();
let visible = app.visible_mrs().count();
let mr_count_label = if visible < total {
format!("{}/{} MRs", visible, total)
} else {
format!("{} MRs", total)
};
// Spinner frames cycled on every tick while fetches are pending.
// Shown both during the initial load (pending_initial_fetches) and auto-refresh cycles
// (pending_refresh_fetches) so the user always knows when the data is being refreshed.
const SPINNER_FRAMES: &[&str] = &["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
let pending = app.pending_initial_fetches + app.pending_refresh_fetches;
let loading_indicator = if pending > 0 {
// Divide by 3 to slow down the animation to ~7 fps — fast enough to feel smooth,
// slow enough for the braille frames to be readable (not a blur).
let frame = SPINNER_FRAMES[(app.spinner_frame / 3) % SPINNER_FRAMES.len()];
format!(" {} Loading ({} pending)…", frame, pending)
} else {
String::new()
};
let title_text =
format!(
" GitLab MR Tracker ({}) │ 🔄 Next refresh: {:02}:{:02} │ {} │ Sort: {} {} │ Filter: {}{}",
app.base_url, mins, secs, mr_count_label, sort_label, order_label, filter_label,
loading_indicator,
);
Table::new(rows, constraints)
.header(header)
.row_highlight_style(
Style::default()
.bg(Color::DarkGray)
.add_modifier(Modifier::BOLD),
)
.highlight_symbol("> ")
.block(
ratatui::widgets::Block::default()
.borders(ratatui::widgets::Borders::ALL)
.title(title_text),
)
}