lupa 0.1.1

Interactive object inspector for Rust — web UI + TUI + snapshot diffing
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
//! Terminal UI mode for the lupa inspector.
//!
//! This module provides a full‑screen interactive terminal interface built with
//! [ratatui](https://ratatui.rs) and [crossterm](https://crates.io/crates/crossterm).
//! It is enabled by the `tui` feature flag.
//!
//! The TUI displays two panels:
//! - **Snapshots** – list of all captured debug dumps; select one to view its
//!   pretty‑printed and syntax‑highlighted content.
//! - **Diffs** – list of computed differences between two snapshots; shows a
//!   coloured line‑by‑line diff.
//!
//! # Key bindings
//! - `↑` / `↓` – move selection in the active list.
//! - `Tab` – switch between Snapshots and Diffs panels.
//! - `Enter` – expand / collapse the detailed view of a snapshot.
//! - `PgUp` / `PgDn` – scroll the detail view.
//! - `q`, `Esc`, or `Ctrl+C` – quit the TUI and return to the terminal.

#![cfg(feature = "tui")]

use std::{io, time::Duration};

use crossterm::{
    event::{self, Event, KeyCode, KeyModifiers},
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{
    backend::CrosstermBackend,
    layout::{Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, List, ListItem, ListState, Paragraph, Wrap},
    Frame, Terminal,
};

use crate::diff::DiffTag;
use crate::state::{DiffEvent, INSPECTOR_STATE, Snapshot};

// ─── Colour palette (Catppuccin Mocha) ───────────────────────────────────────
/// Accent colour – purple, used for titles and active selection borders.
const ACCENT: Color = Color::Rgb(203, 166, 247);
/// Green – used for inserted lines in diffs and string literals.
const GREEN: Color = Color::Rgb(166, 227, 161);
/// Red – used for deleted lines in diffs and boolean `false`.
const RED: Color = Color::Rgb(243, 139, 168);
/// Blue – used for field names in the structured view.
const BLUE: Color = Color::Rgb(137, 180, 250);
/// Cyan – used for type names and enum variants.
const CYAN: Color = Color::Rgb(137, 220, 235);
/// Subtle text colour – used for metadata and less important elements.
const SUBTEXT: Color = Color::Rgb(166, 173, 200);
/// Surface colour – used for highlighted list items and header background.
const SURFACE: Color = Color::Rgb(49, 50, 68);

// ─── Application state ────────────────────────────────────────────────────────
/// Which panel is currently focused.
#[derive(PartialEq, Clone, Copy)]
enum Panel {
    Snapshots,
    Diffs,
}

/// Holds all mutable state of the TUI application.
struct App {
    /// Currently active panel.
    panel: Panel,
    /// List state for the snapshots panel (selection index).
    snap_state: ListState,
    /// List state for the diffs panel (selection index).
    diff_state: ListState,
    /// Whether the snapshot detail view is expanded (full content shown).
    expanded: bool,
    /// Vertical scroll offset in the detail view.
    scroll: u16,
}

impl App {
    /// Creates a new application state with default values.
    fn new() -> Self {
        let mut snap_state = ListState::default();
        snap_state.select(Some(0));
        let mut diff_state = ListState::default();
        diff_state.select(Some(0));
        Self {
            panel: Panel::Snapshots,
            snap_state,
            diff_state,
            expanded: true,
            scroll: 0,
        }
    }

    /// Returns the currently selected snapshot (if any).
    fn selected_snap<'a>(&self, snaps: &'a [Snapshot]) -> Option<&'a Snapshot> {
        self.snap_state.selected().and_then(|i| snaps.get(i))
    }

    /// Returns the currently selected diff event (if any).
    fn selected_diff<'a>(&self, diffs: &'a [DiffEvent]) -> Option<&'a DiffEvent> {
        self.diff_state.selected().and_then(|i| diffs.get(i))
    }

    /// Moves the selection up by one item (if possible).
    fn move_up(&mut self) {
        self.scroll = 0;
        let state = self.active_state_mut();
        let i = state.selected().unwrap_or(0);
        state.select(Some(i.saturating_sub(1)));
    }

    /// Moves the selection down by one item (if possible).
    fn move_down(&mut self, len: usize) {
        self.scroll = 0;
        let state = self.active_state_mut();
        let i = state.selected().unwrap_or(0);
        state.select(Some((i + 1).min(len.saturating_sub(1))));
    }

    /// Returns a mutable reference to the list state of the active panel.
    fn active_state_mut(&mut self) -> &mut ListState {
        match self.panel {
            Panel::Snapshots => &mut self.snap_state,
            Panel::Diffs => &mut self.diff_state,
        }
    }
}

// ─── TUI entry point ──────────────────────────────────────────────────────────
/// Runs the terminal user interface inspector.
///
/// This function:
/// - Switches the terminal to raw mode and the alternate screen.
/// - Starts the main event loop, redrawing on each tick or key press.
/// - Exits when the user presses `q`, `Esc`, or `Ctrl+C`.
///
/// Returns an `io::Result` – on success the terminal is restored to its
/// original state.
pub fn run() -> io::Result<()> {
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen)?;

    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;
    let mut app = App::new();

    loop {
        let snapshots = INSPECTOR_STATE.snapshots();
        let diffs = INSPECTOR_STATE.diffs();

        terminal.draw(|f| draw(f, &mut app, &snapshots, &diffs))?;

        if event::poll(Duration::from_millis(250))? {
            if let Event::Key(key) = event::read()? {
                let len = match app.panel {
                    Panel::Snapshots => snapshots.len(),
                    Panel::Diffs => diffs.len(),
                };
                match (key.code, key.modifiers) {
                    (KeyCode::Char('q'), _) | (KeyCode::Esc, _) | (KeyCode::Char('c'), KeyModifiers::CONTROL) => break,
                    (KeyCode::Tab, _) => {
                        app.panel = match app.panel {
                            Panel::Snapshots => Panel::Diffs,
                            Panel::Diffs => Panel::Snapshots,
                        };
                        app.scroll = 0;
                    }
                    (KeyCode::Up, _) => app.move_up(),
                    (KeyCode::Down, _) => app.move_down(len),
                    (KeyCode::Enter, _) => {
                        app.expanded = !app.expanded;
                        app.scroll = 0;
                    }
                    (KeyCode::PageUp, _) => app.scroll = app.scroll.saturating_sub(10),
                    (KeyCode::PageDown, _) => app.scroll += 10,
                    _ => {}
                }
            }
        }
    }

    disable_raw_mode()?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
    Ok(())
}

// ─── Drawing logic ────────────────────────────────────────────────────────────
/// Main drawing routine – splits the screen and dispatches to panel‑specific
/// renderers.
fn draw(f: &mut Frame, app: &mut App, snapshots: &[Snapshot], diffs: &[DiffEvent]) {
    let area = f.area();

    // Top bar with tabs and key hint.
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(1), Constraint::Min(0)])
        .split(area);

    let tab_str = format!(
        " lupa  │  {}Snapshots ({}){}{}Diffs ({}){}  │  ↑↓ navigate  Tab switch  q quit ",
        if app.panel == Panel::Snapshots { "" } else { "  " },
        snapshots.len(),
        if app.panel == Panel::Snapshots { "" } else { "  " },
        if app.panel == Panel::Diffs { "" } else { "  " },
        diffs.len(),
        if app.panel == Panel::Diffs { "" } else { "  " },
    );
    let header = Paragraph::new(tab_str).style(Style::default().fg(ACCENT).bg(SURFACE));
    f.render_widget(header, chunks[0]);

    // Main area: list (30%) on the left, detail (70%) on the right.
    let main = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Percentage(30), Constraint::Percentage(70)])
        .split(chunks[1]);

    match app.panel {
        Panel::Snapshots => {
            render_snap_list(f, app, snapshots, main[0]);
            render_snap_detail(f, app, snapshots, main[1]);
        }
        Panel::Diffs => {
            render_diff_list(f, app, diffs, main[0]);
            render_diff_detail(f, app, diffs, main[1]);
        }
    }
}

/// Renders the left‑hand list of snapshots.
fn render_snap_list(f: &mut Frame, app: &mut App, snaps: &[Snapshot], area: Rect) {
    let items: Vec<ListItem> = snaps
        .iter()
        .enumerate()
        .map(|(i, s)| ListItem::new(format!(" #{i}  {}", s.label)))
        .collect();

    let list = List::new(items)
        .block(Block::default().borders(Borders::ALL).title(" Snapshots ").border_style(Style::default().fg(ACCENT)))
        .highlight_style(Style::default().bg(SURFACE).fg(ACCENT).add_modifier(Modifier::BOLD))
        .highlight_symbol("");

    f.render_stateful_widget(list, area, &mut app.snap_state);
}

/// Renders the right‑hand detail view of the selected snapshot.
fn render_snap_detail(f: &mut Frame, app: &mut App, snaps: &[Snapshot], area: Rect) {
    let content: Vec<Line> = if let Some(snap) = app.selected_snap(snaps) {
        let mut lines = vec![
            Line::from(vec![
                Span::styled("label: ", Style::default().fg(SUBTEXT)),
                Span::styled(&snap.label, Style::default().fg(ACCENT).add_modifier(Modifier::BOLD)),
            ]),
            Line::from(vec![
                Span::styled("file:  ", Style::default().fg(SUBTEXT)),
                Span::styled(format!("{}:{}", snap.file, snap.line), Style::default().fg(BLUE)),
            ]),
            Line::from(""),
        ];
        if app.expanded {
            lines.extend(highlight_debug(&snap.debug_repr));
        } else {
            lines.push(Line::from(Span::styled(
                "  (press Enter to expand)",
                Style::default().fg(SUBTEXT),
            )));
        }
        lines
    } else {
        vec![Line::from(Span::styled(
            "  No snapshot selected",
            Style::default().fg(SUBTEXT),
        ))]
    };

    let block = Block::default()
        .borders(Borders::ALL)
        .title(" Detail  (Enter expand/collapse  PgUp/PgDn scroll) ")
        .border_style(Style::default().fg(ACCENT));

    let para = Paragraph::new(content)
        .block(block)
        .wrap(Wrap { trim: false })
        .scroll((app.scroll, 0));

    f.render_widget(para, area);
}

/// Renders the left‑hand list of diff events.
fn render_diff_list(f: &mut Frame, app: &mut App, diffs: &[DiffEvent], area: Rect) {
    let items: Vec<ListItem> = diffs
        .iter()
        .enumerate()
        .map(|(i, d)| ListItem::new(format!(" #{i}  {}{}", d.old.label, d.new.label)))
        .collect();

    let list = List::new(items)
        .block(Block::default().borders(Borders::ALL).title(" Diffs ").border_style(Style::default().fg(CYAN)))
        .highlight_style(Style::default().bg(SURFACE).fg(CYAN).add_modifier(Modifier::BOLD))
        .highlight_symbol("");

    f.render_stateful_widget(list, area, &mut app.diff_state);
}

/// Renders the right‑hand detail view of the selected diff.
fn render_diff_detail(f: &mut Frame, app: &mut App, diffs: &[DiffEvent], area: Rect) {
    let content: Vec<Line> = if let Some(diff) = app.selected_diff(diffs) {
        let mut lines = vec![
            Line::from(vec![
                Span::styled("old: ", Style::default().fg(SUBTEXT)),
                Span::styled(&diff.old.label, Style::default().fg(RED)),
                Span::raw(""),
                Span::styled("new: ", Style::default().fg(SUBTEXT)),
                Span::styled(&diff.new.label, Style::default().fg(GREEN)),
            ]),
            Line::from(""),
        ];

        for chunk in &diff.chunks {
            let (prefix, style) = match chunk.tag {
                DiffTag::Insert => ("+ ", Style::default().fg(GREEN)),
                DiffTag::Delete => ("- ", Style::default().fg(RED)),
                DiffTag::Equal => ("  ", Style::default().fg(SUBTEXT)),
            };
            for text_line in chunk.content.lines() {
                lines.push(Line::from(Span::styled(
                    format!("{prefix}{text_line}"),
                    style,
                )));
            }
        }
        lines
    } else {
        vec![Line::from(Span::styled(
            "  No diff selected",
            Style::default().fg(SUBTEXT),
        ))]
    };

    let block = Block::default()
        .borders(Borders::ALL)
        .title(" Diff Detail  (PgUp/PgDn scroll) ")
        .border_style(Style::default().fg(CYAN));

    let para = Paragraph::new(content)
        .block(block)
        .wrap(Wrap { trim: false })
        .scroll((app.scroll, 0));

    f.render_widget(para, area);
}

// ─── Syntax highlighting for Rust debug output ───────────────────────────────
/// Converts a raw debug string into a vector of `Line`s with syntax highlighting.
///
/// It tokenises each line, recognising field names, strings, numbers,
/// boolean literals, type names, and punctuation, then applies colours.
fn highlight_debug(src: &str) -> Vec<Line<'static>> {
    src.lines()
        .map(|line| {
            let mut spans = Vec::new();
            let mut rest = line.to_owned();

            // Preserve leading whitespace (indentation).
            let indent_len = rest.len() - rest.trim_start().len();
            if indent_len > 0 {
                spans.push(Span::raw(rest[..indent_len].to_owned()));
                rest = rest[indent_len..].to_owned();
            }

            // If the line contains a colon, treat the left part as a field name.
            if let Some(colon) = rest.find(':') {
                let key = &rest[..colon];
                let value = rest[colon + 1..].trim().to_owned();
                spans.push(Span::styled(key.to_owned(), Style::default().fg(BLUE)));
                spans.push(Span::raw(": "));
                color_value(&mut spans, &value);
            } else {
                color_value(&mut spans, &rest);
            }

            Line::from(spans)
        })
        .collect()
}

/// Helper function that colours a single value token (string, number, bool, etc.).
fn color_value(spans: &mut Vec<Span<'static>>, v: &str) {
    if v == "true" || v == "false" {
        spans.push(Span::styled(v.to_owned(), Style::default().fg(RED)));
    } else if v.starts_with('"') {
        spans.push(Span::styled(v.to_owned(), Style::default().fg(GREEN)));
    } else if v
        .chars()
        .next()
        .map(|c| c.is_ascii_digit() || c == '-')
        .unwrap_or(false)
    {
        spans.push(Span::styled(v.to_owned(), Style::default().fg(Color::Rgb(250, 179, 135))));
    } else if v.chars().next().map(|c| c.is_uppercase()).unwrap_or(false) {
        // Type name or enum variant – may end with `{`.
        let rest = if let Some(_) = v.strip_suffix('{') {
            spans.push(Span::styled(
                v[..v.len() - 1].trim_end().to_owned(),
                Style::default().fg(CYAN).add_modifier(Modifier::BOLD),
            ));
            Some("{")
        } else {
            spans.push(Span::styled(v.to_owned(), Style::default().fg(CYAN).add_modifier(Modifier::BOLD)));
            None
        };
        if let Some(r) = rest {
            spans.push(Span::styled(r.to_owned(), Style::default().fg(SUBTEXT)));
        }
    } else {
        spans.push(Span::raw(v.to_owned()));
    }
}