Skip to main content

git_nav/ui/
tui.rs

1//! Inline ratatui selector. Arrow keys navigate, type-to-filter narrows
2//! the list, Enter picks, Esc/Ctrl-C quits. Rendered as a bottom-anchored
3//! inline viewport on stderr, so the shell's scrollback context stays put
4//! and stdout stays clean for the caller shell function.
5
6use std::io;
7
8use crossterm::cursor::{Hide, MoveToColumn, MoveUp, Show};
9use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
10use crossterm::execute;
11use crossterm::terminal::{self, Clear, ClearType, disable_raw_mode, enable_raw_mode};
12use ratatui::backend::CrosstermBackend;
13use ratatui::layout::{Constraint, Direction, Layout};
14use ratatui::style::{Color, Modifier, Style};
15use ratatui::text::{Line, Span};
16use ratatui::widgets::{Block, Borders, Cell, Paragraph, Row, Table, TableState};
17use ratatui::{Terminal, TerminalOptions, Viewport};
18
19use crate::git::RepoInfo;
20use crate::ui::fuzzy;
21
22/// Chrome rows around the table (filter line + table header line + hint).
23const CHROME_ROWS: u16 = 4;
24/// Never render smaller than this — below it the widget is unusable.
25const MIN_HEIGHT: u16 = 6;
26/// Never render taller than this even on huge terminals.
27const MAX_HEIGHT: u16 = 20;
28
29/// RAII guard that always restores the terminal on drop — including panic
30/// unwinds. Skipping raw-mode teardown leaves the shell in a state some
31/// terminals (notably Ghostty) read as "a command is still running", which
32/// triggers a spurious close-window warning.
33struct TerminalGuard;
34
35impl TerminalGuard {
36    fn enter() -> crate::Result<Self> {
37        enable_raw_mode()?;
38        execute!(io::stderr(), Hide)?;
39        Ok(Self)
40    }
41}
42
43impl Drop for TerminalGuard {
44    fn drop(&mut self) {
45        let _ = execute!(io::stderr(), Show);
46        let _ = disable_raw_mode();
47    }
48}
49
50/// RAII helper that temporarily points stdout at `/dev/tty`.
51///
52/// Ratatui's inline viewport calls `crossterm::cursor::position()`, which
53/// writes a CPR query (`\x1b[6n`) to stdout and reads the response from
54/// stdin. When the shell wrapper runs `$(git-nav …)`, stdout is a pipe
55/// (not the tty), so the query vanishes and crossterm times out. We
56/// redirect stdout to `/dev/tty` for the picker's lifetime, then restore
57/// it so `println!("{path}")` still lands in the wrapper's pipe.
58#[cfg(unix)]
59struct StdoutToTty {
60    saved: libc::c_int,
61}
62
63#[cfg(unix)]
64impl StdoutToTty {
65    fn install() -> crate::Result<Self> {
66        use std::fs::OpenOptions;
67        use std::io::Write as _;
68        use std::os::unix::io::AsRawFd;
69
70        io::stdout().flush().ok();
71        let saved = unsafe { libc::dup(libc::STDOUT_FILENO) };
72        if saved < 0 {
73            return Err(io::Error::last_os_error().into());
74        }
75        let tty = match OpenOptions::new().write(true).open("/dev/tty") {
76            Ok(f) => f,
77            Err(e) => {
78                unsafe { libc::close(saved) };
79                return Err(e.into());
80            }
81        };
82        let rc = unsafe { libc::dup2(tty.as_raw_fd(), libc::STDOUT_FILENO) };
83        if rc < 0 {
84            let e = io::Error::last_os_error();
85            unsafe { libc::close(saved) };
86            return Err(e.into());
87        }
88        Ok(Self { saved })
89    }
90}
91
92#[cfg(unix)]
93impl Drop for StdoutToTty {
94    fn drop(&mut self) {
95        use std::io::Write as _;
96        io::stdout().flush().ok();
97        unsafe {
98            libc::dup2(self.saved, libc::STDOUT_FILENO);
99            libc::close(self.saved);
100        }
101    }
102}
103
104pub fn select(infos: &[RepoInfo]) -> crate::Result<Option<usize>> {
105    // Order matters: the stdout redirect must exist before ratatui's
106    // first draw (which queries cursor position), and must outlive the
107    // terminal guard so cleanup ANSI sequences also land on the tty.
108    #[cfg(unix)]
109    let _stdout_redirect = StdoutToTty::install()?;
110    let _guard = TerminalGuard::enter()?;
111
112    let (_, term_h) = terminal::size().unwrap_or((80, 24));
113    let height = picker_height(term_h, infos.len());
114
115    let backend = CrosstermBackend::new(io::stderr());
116    let mut terminal = Terminal::with_options(
117        backend,
118        TerminalOptions {
119            viewport: Viewport::Inline(height),
120        },
121    )?;
122
123    let result = run_loop(&mut terminal, infos);
124    drop(terminal);
125
126    // Reclaim the picker's rows so the shell prompt returns to the line
127    // where it started — `terminal.clear()` on an inline viewport only
128    // wipes the content, it doesn't remove the reserved space. Walking
129    // the cursor up to the viewport's top row and clearing from there
130    // to the end of the screen collapses the whole picker area, so the
131    // next output (a shell prompt) begins exactly where the picker did.
132    let _ = execute!(
133        io::stderr(),
134        MoveToColumn(0),
135        MoveUp(height.saturating_sub(1)),
136        Clear(ClearType::FromCursorDown),
137    );
138
139    result
140}
141
142fn picker_height(term_h: u16, repo_count: usize) -> u16 {
143    let ideal = (repo_count as u16).saturating_add(CHROME_ROWS + 1);
144    let capped = ideal.clamp(MIN_HEIGHT, MAX_HEIGHT);
145    let cap_by_term = term_h.saturating_sub(1).max(MIN_HEIGHT);
146    capped.min(cap_by_term)
147}
148
149fn run_loop(
150    terminal: &mut Terminal<CrosstermBackend<io::Stderr>>,
151    infos: &[RepoInfo],
152) -> crate::Result<Option<usize>> {
153    let mut filter = String::new();
154    let mut state = TableState::default();
155    state.select(Some(0));
156
157    loop {
158        let filtered = apply_filter(infos, &filter);
159        clamp_selection(&mut state, filtered.len());
160
161        terminal.draw(|f| draw(f, infos, &filtered, &filter, &mut state))?;
162
163        let Event::Key(KeyEvent {
164            code,
165            modifiers,
166            kind,
167            ..
168        }) = event::read()?
169        else {
170            continue;
171        };
172        if kind != KeyEventKind::Press {
173            continue;
174        }
175
176        match code {
177            KeyCode::Esc => return Ok(None),
178            KeyCode::Char('c') if modifiers.contains(KeyModifiers::CONTROL) => return Ok(None),
179            KeyCode::Enter => {
180                if let Some(cur) = state.selected() {
181                    if let Some(&idx) = filtered.get(cur) {
182                        return Ok(Some(idx));
183                    }
184                }
185            }
186            KeyCode::Up => move_selection(&mut state, -1, filtered.len()),
187            KeyCode::Down => move_selection(&mut state, 1, filtered.len()),
188            KeyCode::PageUp => move_selection(&mut state, -10, filtered.len()),
189            KeyCode::PageDown => move_selection(&mut state, 10, filtered.len()),
190            KeyCode::Home => {
191                if filtered.is_empty() {
192                    state.select(None);
193                } else {
194                    state.select(Some(0));
195                }
196            }
197            KeyCode::End => {
198                if filtered.is_empty() {
199                    state.select(None);
200                } else {
201                    state.select(Some(filtered.len() - 1));
202                }
203            }
204            KeyCode::Backspace => {
205                filter.pop();
206            }
207            KeyCode::Char(c) => filter.push(c),
208            _ => {}
209        }
210    }
211}
212
213fn apply_filter(infos: &[RepoInfo], filter: &str) -> Vec<usize> {
214    if filter.is_empty() {
215        return (0..infos.len()).collect();
216    }
217    infos
218        .iter()
219        .enumerate()
220        .filter(|(_, r)| {
221            fuzzy::matches(filter, &r.name)
222                || fuzzy::matches(filter, &r.org)
223                || fuzzy::matches(filter, &r.branch)
224        })
225        .map(|(i, _)| i)
226        .collect()
227}
228
229fn clamp_selection(state: &mut TableState, len: usize) {
230    if len == 0 {
231        state.select(None);
232        return;
233    }
234    let cur = state.selected().unwrap_or(0);
235    state.select(Some(cur.min(len - 1)));
236}
237
238fn move_selection(state: &mut TableState, delta: i32, len: usize) {
239    if len == 0 {
240        return;
241    }
242    let cur = state.selected().unwrap_or(0) as i32;
243    let next = (cur + delta).clamp(0, len as i32 - 1) as usize;
244    state.select(Some(next));
245}
246
247fn draw(
248    f: &mut ratatui::Frame,
249    infos: &[RepoInfo],
250    filtered: &[usize],
251    filter: &str,
252    state: &mut TableState,
253) {
254    let chunks = Layout::default()
255        .direction(Direction::Vertical)
256        .constraints([
257            Constraint::Length(1), // filter line
258            Constraint::Min(2),    // table (with top separator)
259            Constraint::Length(2), // hint (with top separator)
260        ])
261        .split(f.area());
262
263    let counter = format!("{}/{}", filtered.len(), infos.len());
264    let filter_line = Paragraph::new(Line::from(vec![
265        Span::styled(" filter: ", Style::default().fg(Color::DarkGray)),
266        Span::styled(
267            filter,
268            Style::default()
269                .fg(Color::Yellow)
270                .add_modifier(Modifier::BOLD),
271        ),
272        Span::styled(
273            "▏",
274            Style::default()
275                .fg(Color::Yellow)
276                .add_modifier(Modifier::SLOW_BLINK),
277        ),
278        Span::raw("  "),
279        Span::styled(counter, Style::default().fg(Color::DarkGray)),
280    ]));
281    f.render_widget(filter_line, chunks[0]);
282
283    let header = Row::new(vec!["REPO", "ORG", "BRANCH", "SHA", "STATUS"]).style(
284        Style::default()
285            .fg(Color::DarkGray)
286            .add_modifier(Modifier::BOLD),
287    );
288
289    let rows: Vec<Row> = filtered.iter().map(|&i| build_row(&infos[i])).collect();
290
291    let table = Table::new(
292        rows,
293        [
294            Constraint::Percentage(28),
295            Constraint::Percentage(18),
296            Constraint::Percentage(22),
297            Constraint::Length(8),
298            Constraint::Percentage(20),
299        ],
300    )
301    .header(header)
302    .row_highlight_style(
303        Style::default()
304            .bg(Color::DarkGray)
305            .add_modifier(Modifier::BOLD),
306    )
307    .highlight_symbol("▶ ")
308    .block(
309        Block::default()
310            .borders(Borders::TOP)
311            .border_style(Style::default().fg(Color::DarkGray)),
312    );
313    f.render_stateful_widget(table, chunks[1], state);
314
315    let hint = Paragraph::new(Line::from(vec![
316        Span::raw(" "),
317        Span::styled("↑↓", Style::default().fg(Color::Cyan)),
318        Span::raw(" move   "),
319        Span::styled("type", Style::default().fg(Color::Cyan)),
320        Span::raw(" filter   "),
321        Span::styled("enter", Style::default().fg(Color::Cyan)),
322        Span::raw(" cd   "),
323        Span::styled("esc", Style::default().fg(Color::Cyan)),
324        Span::raw(" quit"),
325    ]))
326    .block(
327        Block::default()
328            .borders(Borders::TOP)
329            .border_style(Style::default().fg(Color::DarkGray)),
330    );
331    f.render_widget(hint, chunks[2]);
332}
333
334fn build_row(info: &RepoInfo) -> Row<'static> {
335    Row::new(vec![
336        Cell::from(info.name.clone()),
337        Cell::from(info.org.clone()).style(Style::default().fg(Color::Blue)),
338        Cell::from(info.branch.clone()).style(Style::default().fg(Color::Magenta)),
339        Cell::from(info.sha.clone()).style(Style::default().fg(Color::DarkGray)),
340        Cell::from(status_line(info)),
341    ])
342}
343
344fn status_line(info: &RepoInfo) -> Line<'static> {
345    let mut spans: Vec<Span<'static>> = Vec::new();
346    if info.dirty > 0 {
347        spans.push(Span::styled(
348            format!("{} changed", info.dirty),
349            Style::default().fg(Color::Yellow),
350        ));
351    } else {
352        spans.push(Span::styled("clean", Style::default().fg(Color::Green)));
353    }
354    if info.ahead > 0 {
355        spans.push(Span::raw(" "));
356        spans.push(Span::styled(
357            format!("↑{}", info.ahead),
358            Style::default().fg(Color::Cyan),
359        ));
360    }
361    if info.behind > 0 {
362        spans.push(Span::raw(" "));
363        spans.push(Span::styled(
364            format!("↓{}", info.behind),
365            Style::default().fg(Color::Red),
366        ));
367    }
368    Line::from(spans)
369}
370
371#[cfg(test)]
372mod tests {
373    use super::*;
374
375    fn ri(name: &str, org: &str, branch: &str) -> RepoInfo {
376        RepoInfo {
377            name: name.into(),
378            path: format!("/tmp/{name}"),
379            branch: branch.into(),
380            sha: "abc1234".into(),
381            ahead: 0,
382            behind: 0,
383            dirty: 0,
384            org: org.into(),
385        }
386    }
387
388    #[test]
389    fn empty_filter_returns_all() {
390        let infos = vec![ri("a", "o", "main"), ri("b", "o", "main")];
391        assert_eq!(apply_filter(&infos, ""), vec![0, 1]);
392    }
393
394    #[test]
395    fn filter_matches_name_org_or_branch() {
396        let infos = vec![
397            ri("api-gateway", "acme", "main"),
398            ri("billing-svc", "acme", "feat/x"),
399            ri("website", "personal", "main"),
400        ];
401        assert_eq!(apply_filter(&infos, "bill"), vec![1]);
402        assert_eq!(apply_filter(&infos, "person"), vec![2]);
403        assert_eq!(apply_filter(&infos, "feat"), vec![1]);
404    }
405
406    #[test]
407    fn clamp_selection_handles_empty() {
408        let mut s = TableState::default();
409        s.select(Some(5));
410        clamp_selection(&mut s, 0);
411        assert_eq!(s.selected(), None);
412    }
413
414    #[test]
415    fn clamp_selection_caps_at_last() {
416        let mut s = TableState::default();
417        s.select(Some(10));
418        clamp_selection(&mut s, 3);
419        assert_eq!(s.selected(), Some(2));
420    }
421
422    #[test]
423    fn move_selection_clamps_edges() {
424        let mut s = TableState::default();
425        s.select(Some(0));
426        move_selection(&mut s, -1, 5);
427        assert_eq!(s.selected(), Some(0));
428        move_selection(&mut s, 100, 5);
429        assert_eq!(s.selected(), Some(4));
430    }
431
432    #[test]
433    fn picker_height_scales_with_repo_count() {
434        // small: chrome + 1 extra + repos, but clamped to MIN
435        assert_eq!(picker_height(50, 1), MIN_HEIGHT);
436        // medium: fits without clamping
437        assert_eq!(picker_height(50, 10), 10 + CHROME_ROWS + 1);
438        // large: clamped at MAX
439        assert_eq!(picker_height(50, 100), MAX_HEIGHT);
440    }
441
442    #[test]
443    fn picker_height_respects_short_terminal() {
444        // Terminal too short to fit our ideal — cap to term_h - 1.
445        let h = picker_height(8, 20);
446        assert_eq!(h, 7);
447    }
448}