Skip to content

feat(layout): declarative layout engine with nested rows/cols (#3) - #24

Merged
unhappychoice merged 3 commits into
mainfrom
feat/3-layout-engine
Apr 21, 2026
Merged

unhappychoice merged 3 commits into
mainfrom
feat/3-layout-engine

Conversation

@unhappychoice

@unhappychoice unhappychoice commented Apr 21, 2026 •

Copy link
Copy Markdown
Owner

Summary

Third axis of the 3-axis model. layout::draw walks a declarative Layout tree and hands each leaf rect to render_payload. Config (#2) will later drive the tree from TOML; for now main.rs constructs it programmatically.

Layout primitives

```rust
Layout::rows(vec![...]) // vertical stack
Layout::cols(vec![...]) // horizontal stack
Layout::widget(id) // leaf referencing a widget by id
Layout::empty // explicit blank cell
```

Size constraints (full mapping to Ratatui `Constraint`):
`Child::fill(w) / length(n) / min(n) / max(n) / percentage(p)`.

Panels (titles + borders)

Both `Widget` and `Stack` nodes can carry an optional `Panel` that draws a `Block` with a title and border:

```rust
Layout::widget("git").titled("Git").bordered(BorderStyle::Rounded)

Layout::cols(vec![
Child::fill(1, Layout::widget("cpu")),
Child::fill(1, Layout::widget("mem")),
Child::fill(1, Layout::widget("disk")),
]).titled("System")
```

BorderStyle covers Plain / Rounded / Thick / Double.

Important redesign: `Payload.title` was removed and `render_payload` no longer auto-wraps widgets in a `Block`. Decoration is now purely a layout concern — plugins and fetchers produce raw data, config decides how to dress it. This makes the Group pattern (shared outer border around multiple widgets) structurally possible without double-lining individual leaves.

Design

  • Nested ratio (Fill) instead of wtfutil's absolute grid — reflows cleanly on resize.
  • Layout references widgets by id; payload map is provided separately so fetchers and layout decouple.
  • Missing id is silently skipped (no panic); layout + widgets evolve independently.
  • No Block is drawn unless a Panel is explicitly set — double borders are impossible.

Test plan

  • cargo build (zero warnings)
  • cargo test (33 passed: 12 payload + 12 render + 9 layout)
  • cargo clippy --all-targets -- -D warnings
  • cargo fmt --check
  • CI (ubuntu / macos / windows)

Closes #3.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Introduced a composable UI layout system enabling flexible stacking of components with vertical or horizontal arrangement.
    • Added configurable panel styling with optional titles and border options (plain, rounded, thick, double).
  • Refactor

    • Migrated widget rendering to the new layout architecture.
    • Simplified widget rendering by eliminating redundant border layers.
    • Moved title management from individual widgets to layout panels.

The third axis of the 3-axis model. Takes a Layout tree + a widget-id
to Payload map, walks the tree, and hands each leaf rect to
render_payload. Config system (#2) will drive this declaratively from
TOML later; for now main.rs constructs the tree programmatically.

Layout primitives:
- Layout::rows / Layout::cols — nested stacks
- Layout::widget(id) — leaf referencing a widget by id
- Layout::empty — explicit blank cell

Child sizing:
- Child::fill(weight) — Ratatui Constraint::Fill (proportional)
- Child::length(n)    — Ratatui Constraint::Length (exact)
- Child::min(n)       — Ratatui Constraint::Min (flex with minimum)

main.rs demo now drives the render path through layout::draw with an
explicit demo_layout tree + demo_widgets map, replacing the hardcoded
Layout::vertical calls.

Refs #3

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Apr 21, 2026 •

Copy link
Copy Markdown

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

A new composable layout system has been introduced via src/layout.rs enabling nested stacks, widgets, and panels with flexible sizing strategies. The Payload struct's title field has been removed and delegated to the layout system's panel abstraction. The demo application now uses the new layout API instead of direct ratatui layout construction, with corresponding updates to render modules and test utilities.

Changes

Cohort / File(s) Summary
Layout System
src/layout.rs
New 410-line module implementing composable UI layouts with Layout enum (Stack/Widget/Empty), Direction (Vertical/Horizontal), Size constraints (Fill/Length/Min/Max/Percentage), Panel with titles and border styles, and recursive draw function with unit tests.
Main Demo Migration
src/main.rs
Refactored drawing flow to use new Layout API via demo_layout() and HashMap-based demo_widgets() instead of ratatui primitives; replaced fixed-size widget array with WidgetId-keyed payload map; removed titled() helper and Payload.title usage.
Payload Structure
src/payload.rs
Removed title: Option<String> field from Payload struct and updated unit tests to reflect removal.
Render Module Refactoring
src/render/mod.rs
Removed Block wrapping logic and build_block helper from render_payload, rendering payloads directly to the provided area without inner rectangle computation.
Test Utilities
src/render/test_utils.rs
Added render_to_buffer_with(root: &Layout, widgets: &HashMap<WidgetId, Payload>, width: u16, height: u16) -> Buffer function to support layout-based rendering in tests.
Render Test Helpers
src/render/{bar_chart,bignum,gauge,image,line_chart,sparkline}.rs
Removed title: None field initialization from private payload() test constructors.
List & Text Render Tests
src/render/{list,text}.rs
Removed title: None from test helpers and adjusted line index assertions due to removed block wrapping (reading from line 0 instead of 1).

Sequence Diagram

sequenceDiagram
    participant App as Application
    participant Layout as Layout System
    participant Panel as Panel
    participant Widget as Widget Renderer
    participant Payload as Payload Map
    participant Frame as Ratatui Frame

    App->>Layout: draw(frame, area, &layout, &widgets)
    alt Layout is Stack
        Layout->>Layout: Split area by Direction & Sizes
        loop For each Child
            Layout->>Layout: Compute child rectangle
            Layout->>Layout: Recursively draw child
        end
    end
    alt Layout is Widget
        Layout->>Panel: Check if Panel exists
        alt Panel Present
            Panel->>Frame: Build Block with border/title
            Panel->>Frame: Get inner rectangle
        end
        Layout->>Payload: Lookup WidgetId
        alt Widget Found
            Payload->>Widget: Render Payload.body
            Widget->>Frame: Draw to rectangle
        end
    end
    alt Layout is Empty
        Layout->>Frame: Render nothing
    end
    Frame->>App: Return rendered frame
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

Poem

🐰 A layout system hops into view,
Nested stacks with panels too!
Widgets dance in rows and cols,
Sizing fills our design goals—
Terminal ui takes control! 🌳✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 28.57% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically summarizes the main change: adding a declarative layout engine with support for nested rows/columns.
Linked Issues check ✅ Passed The PR implements all core requirements from #3: nested ratio rows/cols via Layout::rows/cols, empty widget support, responsive terminal resize via ratatui Constraint mapping, engine dispatches to renderers via render_payload, and layout-to-payload decoupling via WidgetId.
Out of Scope Changes check ✅ Passed All changes are in-scope: new layout module, refactored main.rs to use the layout API, removed title field from Payload (moved to Layout::Panel as per PR objectives), and updated test helpers consistently.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/3-layout-engine

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.

unhappychoice and others added 2 commits April 21, 2026 09:59
Completes the mapping to Ratatui's Constraint repertoire so layouts can
express caps (Max) and explicit percentages. Fill / Length / Min cover
the common case; Max / Percentage round out the long tail.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Fixes a category mistake that made group-style borders impossible
without double-drawing:

- Payload.title and the auto-Block in render_payload tangled decoration
  with data. Result: a single widget got a border automatically, but
  wrapping several widgets in a shared outer frame would double-line
  every leaf.
- Title and borders are layout concerns, not data concerns. The plugin
  protocol and widget fetchers should produce raw data; config decides
  how to dress it.

Redesign:
- Payload: dropped the `title` field. Plugins now emit pure data.
- render::render_payload: no longer wraps in a Block. Each renderer
  draws into the area it is given, bare.
- layout::Layout gained an optional `Panel { title, border }` on both
  Stack and Widget variants. Panel draws a Block (title + BorderStyle:
  Plain / Rounded / Thick / Double) around any subtree.
- Ergonomics: `Layout::widget("git").titled("Git").bordered(Rounded)`
  chains decoration; `Layout::rows(...).titled("System")` makes a
  bordered group around multiple widgets.
- main.rs demo updated to decorate each leaf explicitly via .titled(...).

Double borders are now structurally impossible: no Block is drawn
unless a Panel is present on that specific Layout node.

Co-Authored-By: Claude Opus 4.7 (1M context) <[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.

core: Layout engine (widget positioning)

1 participant