Skip to content

feat: implement basic ratatui UI layout - #15

Merged
unhappychoice merged 3 commits into
mainfrom
feat/ratatui-ui-layout
Nov 8, 2025
Merged

unhappychoice merged 3 commits into
mainfrom
feat/ratatui-ui-layout

Conversation

@unhappychoice

@unhappychoice unhappychoice commented Nov 8, 2025 •

Copy link
Copy Markdown
Owner

Summary

Implement comprehensive 4-pane terminal UI layout using ratatui and crossterm.

Layout

┌──────────┬──────────┐
│          │          │
│ fileTree │  editor  │
│          │  (60%)   │
├──────────┼──────────┤
│ fileTree │ terminal │
│  (30%)   │  (40%)   │
└──────────┴──────────┘
│   status bar (3)    │
└─────────────────────┘

Changes

New src/ui.rs module

UI struct:

  • Lifecycle management (initialization, cleanup)
  • Event loop with non-blocking polling
  • Graceful shutdown handling

Terminal setup:

  • Alternate screen mode
  • Raw mode for key capture
  • Mouse capture support
  • Proper restoration on exit

Layout implementation:

  • Main vertical split: content + status bar
  • Content horizontal split: file tree (30%) + right side (70%)
  • Right side vertical split: editor (60%) + terminal (40%)
  • Status bar: 3 lines at bottom

Four panes with placeholder content:

  1. File Tree (left, Cyan border)

    • Shows directory structure
    • Lists source files
  2. Editor (right-top, Green border)

    • Displays code content
    • Will show animated typing
  3. Terminal (right-bottom, Yellow border)

    • Shows git command output
    • Displays commit log
  4. Status Bar (bottom, White border)

    • Commit metadata
    • Author and hash info
    • Keyboard hints

Main.rs integration

  • Import and initialize UI module
  • Launch UI in main function
  • Placeholder for git integration (TODO)

Features

✅ Responsive layout with percentage-based sizing
✅ Colored borders for visual separation
✅ Non-blocking event handling (100ms poll)
✅ Exit on 'q' or Esc key
✅ Proper terminal cleanup on exit
✅ Alternate screen (doesn't mess up shell history)

Test plan

  • cargo build succeeds
  • Terminal initialization works
  • Layout renders correctly
  • All four panes display
  • Keyboard input handled
  • Exit works properly (q/Esc)
  • Terminal restored correctly

Next steps

  • Integrate with git module to load actual commit data
  • Implement file tree rendering with real files
  • Add syntax highlighting to editor pane
  • Implement typing animation
  • Add scrolling support

Resolves #6

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • New Features
    • Replaced command-line interface with an interactive terminal UI
    • Added multi-pane layout featuring file tree, editor, terminal, and status bar
    • Enabled keyboard-based navigation with exit controls (q or Escape)

Add comprehensive 4-pane UI layout with ratatui:

Layout structure:
```
┌──────────┬──────────┐
│          │          │
│ fileTree │  editor  │
│          │          │
├──────────┼──────────┤
│ fileTree │ terminal │
│          │          │
└──────────┴──────────┘
│      status         │
└─────────────────────┘
```

New ui.rs module:
- UI struct with lifecycle management
- Terminal initialization and cleanup
- Proper alternate screen handling
- Mouse capture support
- Event handling (keyboard input)
- Exit on 'q' or Esc

Four panes:
1. File Tree (left, 30%): displays file structure
2. Editor (right-top, 60%): shows code with syntax highlighting
3. Terminal (right-bottom, 40%): git command output
4. Status Bar (bottom, 3 lines): commit metadata and controls

Features:
- Responsive layout with percentage-based sizing
- Colored borders for each pane (Cyan/Green/Yellow/White)
- Proper terminal restoration on exit
- Non-blocking event polling (100ms)
- Graceful shutdown

Resolves #6

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@coderabbitai

coderabbitai Bot commented Nov 8, 2025 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@unhappychoice has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 23 minutes and 1 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 40d1407 and 51662c7.

📒 Files selected for processing (7)
  • src/main.rs (2 hunks)
  • src/panes/editor.rs (1 hunks)
  • src/panes/file_tree.rs (1 hunks)
  • src/panes/mod.rs (1 hunks)
  • src/panes/status_bar.rs (1 hunks)
  • src/panes/terminal.rs (1 hunks)
  • src/ui.rs (1 hunks)

Walkthrough

This PR introduces a new terminal UI system that replaces Git-repo driven logic in the main function. A new UI module is created using Ratatui and Crossterm, featuring a multi-pane layout with file tree, editor, terminal, and status bar. The main function now initializes and runs the UI instead of loading repository data.

Changes

Cohort / File(s) Summary
Main entry point refactoring
src/main.rs
Replaces Git-repo driven logic with UI initialization. Removes repository loading, commit selection, and info printing. Adds UI module import and calls UI::new().run(). TODO comment added for future git module integration.
Terminal UI implementation
src/ui.rs
New file implementing terminal UI with Ratatui and Crossterm. Adds UI struct with event loop, multi-pane layout renderer (file tree, editor, terminal, status bar), input handling ('q' and Escape to quit), and proper terminal setup/cleanup with error propagation.

Sequence Diagram

sequenceDiagram
    participant Main as main()
    participant UI as UI::new()
    participant Terminal as Terminal Setup
    participant EventLoop as Event Loop
    participant Render as Render Pipeline
    participant Input as Input Handler

    Main->>UI: new()
    Main->>UI: run()
    UI->>Terminal: enable_raw_mode()
    UI->>Terminal: enter_alternate_screen()
    UI->>EventLoop: start
    
    loop Until quit
        EventLoop->>Input: poll for events
        Input-->>EventLoop: key press / resize
        alt Input is 'q' or Escape
            EventLoop->>EventLoop: set should_quit = true
        else Other input
            EventLoop->>EventLoop: ignore
        end
        EventLoop->>Render: draw frame
        Render->>Render: render_file_tree()
        Render->>Render: render_editor()
        Render->>Render: render_terminal()
        Render->>Render: render_status_bar()
        Render-->>EventLoop: frame drawn
    end
    
    EventLoop->>Terminal: disable_raw_mode()
    EventLoop->>Terminal: leave_alternate_screen()
    Terminal-->>UI: cleanup complete
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Areas for extra attention:
    • Event loop implementation and input handling logic for completeness
    • Terminal initialization and cleanup sequence to ensure proper resource management
    • Layout calculations for multi-pane rendering and area allocation
    • Error propagation through Result types in the render pipeline

Possibly related PRs

  • PR #12: Initial project setup and dependencies (ratatui, crossterm) that this PR builds upon for terminal UI implementation.

Poem

A terminal blooms in shades of green,
Four panes dance where code is seen—
Files on left, editor's bright glow,
Terminal whispers, status below. 🐰✨

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: implement basic ratatui UI layout' directly and specifically describes the main change in the pull request, which introduces a new UI module with ratatui-based terminal UI implementation.
Linked Issues check ✅ Passed The pull request successfully implements all primary coding requirements from issue #6: terminal initialization/cleanup, full-screen layout with editor pane and status bar, static content display, terminal restoration, and input handling for clean exit.
Out of Scope Changes check ✅ Passed All changes are within scope of issue #6; the PR implements the UI module, layout structure, and event handling as specified, with no unrelated modifications to unrelated components.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Make terminal pane smaller as requested:
- Editor: 60% -> 80%
- Terminal: 40% -> 20%

This gives more space to the editor pane for code display.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8ec9a9c and 40d1407.

📒 Files selected for processing (2)
  • src/main.rs (2 hunks)
  • src/ui.rs (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/main.rs (1)
src/ui.rs (1)
  • new (22-24)
🔇 Additional comments (8)
src/ui.rs (5)

46-67: LGTM!

The event loop implementation is clean with non-blocking polling and appropriate quit handling.


91-92: Layout split doesn't match PR description.

The code implements an 80/20 split between editor and terminal, but the PR description specifies "editor (60%) above terminal (40%)".

If the 60/40 split is the intended design, apply this diff:

         let right_layout = Layout::default()
             .direction(Direction::Vertical)
             .constraints([
-                Constraint::Percentage(80),  // Editor
-                Constraint::Percentage(20),  // Terminal
+                Constraint::Percentage(60),  // Editor
+                Constraint::Percentage(40),  // Terminal
             ])
             .split(content_layout[1]);

102-120: LGTM!

The file tree placeholder is appropriate for the current implementation stage.


122-153: LGTM!

Both editor and terminal panes have appropriate placeholder content and clean implementations.


155-167: LGTM!

The status bar implementation is clean and provides appropriate placeholder information.

src/main.rs (3)

2-2: LGTM!

The UI module integration is clean and straightforward.

Also applies to: 8-8


69-86: LGTM!

The main function cleanly transitions to a UI-driven flow while preserving argument validation for future git integration. The TODO comment clearly indicates the next integration steps.


88-180: Verify whether print_commit_info should be retained.

This function is no longer called after the UI integration. While the TODO comments suggest it may be useful for future git integration, it's currently unused code that will generate warnings.

Consider either:

  1. Removing it now and re-adding when needed for git integration
  2. Adding #[allow(dead_code)] if keeping it for near-term use
  3. Moving it to the git module if it belongs there

Which approach aligns with your development plan?

Comment thread src/ui.rs
Comment on lines +26 to +44
pub fn run(&mut self) -> Result<()> {
enable_raw_mode()?;
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;

let result = self.run_loop(&mut terminal);

disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;

result
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Cleanup errors may mask the original error from run_loop.

If run_loop returns an error and any subsequent cleanup operation (lines 35-41) also fails, the cleanup error will be returned instead of the original error from run_loop. This can make debugging difficult by hiding the root cause.

Consider preserving the original error:

 pub fn run(&mut self) -> Result<()> {
     enable_raw_mode()?;
     let mut stdout = io::stdout();
     execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
     let backend = CrosstermBackend::new(stdout);
     let mut terminal = Terminal::new(backend)?;

     let result = self.run_loop(&mut terminal);

-    disable_raw_mode()?;
-    execute!(
-        terminal.backend_mut(),
-        LeaveAlternateScreen,
-        DisableMouseCapture
-    )?;
-    terminal.show_cursor()?;
-
-    result
+    // Always attempt cleanup, but preserve the original error if both fail
+    let cleanup_result = (|| -> Result<()> {
+        disable_raw_mode()?;
+        execute!(
+            terminal.backend_mut(),
+            LeaveAlternateScreen,
+            DisableMouseCapture
+        )?;
+        terminal.show_cursor()?;
+        Ok(())
+    })();
+
+    // Return the first error encountered
+    result.and(cleanup_result)
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
pub fn run(&mut self) -> Result<()> {
enable_raw_mode()?;
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
let result = self.run_loop(&mut terminal);
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
result
}
pub fn run(&mut self) -> Result<()> {
enable_raw_mode()?;
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
let result = self.run_loop(&mut terminal);
// Always attempt cleanup, but preserve the original error if both fail
let cleanup_result = (|| -> Result<()> {
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
Ok(())
})();
// Return the first error encountered
result.and(cleanup_result)
}

Create separate files for each UI pane component:
- file_tree.rs: File tree pane with cyan border
- editor.rs: Editor pane with green border
- terminal.rs: Terminal pane with yellow border (20% height)
- status_bar.rs: Status bar pane with white border

This improves code organization and maintainability.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Build basic ratatui UI layout

1 participant