Skip to content

refactor(render): data-shape Body + Renderer registry (3-axis) (#32) - #34

Merged
unhappychoice merged 12 commits into
mainfrom
refactor/32-renderer-registry
Apr 21, 2026
Merged

unhappychoice merged 12 commits into
mainfrom
refactor/32-renderer-registry

Conversation

@unhappychoice

@unhappychoice unhappychoice commented Apr 21, 2026 •

Copy link
Copy Markdown
Owner

Decouples the three axes (fetcher × data-shape × renderer) that had collapsed into two in the original implementation. Makes `config.render` actually do something and unblocks #17 (theming) and future renderer additions (ascii art, animated, custom charts) without further architecture churn.

Before

  • `Body` variants were named after renderers (`Bignum`, `Sparkline`, `LineChart`, etc.). A fetcher emitting `Body::Bignum` was bound to the one bignum renderer.
  • `WidgetConfig.render` was declared but never read.
  • No way to say "show this clock as plain text instead of big-text", or "render this gauge as a donut instead of a bar" — required a new fetcher per visual form.

After

Body is shape-named: `Lines` (merged Text + Bignum), `Entries` (was List), `Ratio` (was Gauge), `NumberSeries` (was Sparkline), `PointSeries` (was LineChart), `Bars` (was BarChart), `Image`. Serde tag renamed `render` → `shape`.

`Renderer` trait + `Registry` (mirrors `fetcher::Registry`). Each Renderer declares `name`, `accepts(&[Shape])`, and renders `(Body, RenderOptions)`. 8 builtins:

renderer shape implementation
`simple` `Lines` ratatui `Paragraph`
`bignum_tui` `Lines` `tui-big-text`, reads `pixel_size`
`list` `Entries` ratatui `Table`
`gauge` `Ratio` ratatui `Gauge`
`sparkline` `NumberSeries` ratatui `Sparkline`
`chart_line` `PointSeries` ratatui `Chart`
`bar_chart` `Bars` ratatui `BarChart`
`image` `Image` `ratatui-image`

Two renderers already registered for `Lines` (`simple` + `bignum_tui`) proves shape → N renderers.

`RenderSpec` in config, two-form TOML via `#[serde(untagged)]`:

```toml
render = "simple" # defaults
render = { type = "bignum_tui", pixel_size = "quadrant" } # with options
```

Absent = default renderer for the shape. Dispatch compat-checks `shape` vs `renderer.accepts`; mismatches and unknown names draw an inline error instead of panicking.

What's out of scope (follow-ups)

Test plan

  • `cargo fmt --check`
  • `cargo clippy --all-targets -- -D warnings`
  • `cargo test` (131 passed, incl. short/full RenderSpec parsing, registry coverage, default-renderer-per-shape compat, Lines has multiple renderers, pixel_size option parsing)
  • Manual: `cargo run` with the committed `.splashboard/config.toml` renders using `render = { type = "bignum_tui", pixel_size = "quadrant" }` for the clock

Closes #32.

Summary by CodeRabbit

Release Notes

  • New Features

    • Added support for calendar, scatter plot, and table renderers
    • Introduced animated typewriter and ASCII art text rendering options
    • New line gauge renderer for compact progress bars
    • Added configurable viewport height option in dashboard settings
  • Configuration

    • Updated render configuration system with optional renderer specifications
    • Added example dashboard configuration demonstrating new renderer capabilities
  • Dependencies

    • Updated ratatui with calendar widget support
    • Added time and figlet-rs libraries for enhanced rendering features

Previously the Body enum was render-named (Bignum / Sparkline /
LineChart / BarChart / Gauge / Text / List / Image), which collapsed
the 1:N relationship between a data shape and the renderers that
could consume it. A clock output was stuck on the "bignum" renderer
by virtue of being a \`Body::Bignum\`; there was no way to show the
same value as plain text, ASCII art, or an animated flip without
inventing a new fetcher. And \`WidgetConfig.render\` was declared
but never consulted.

Decouple the three axes:

**Body is now shape-named.** \`Lines\` (merged Text + Bignum, both
are just strings), \`Entries\` (was List), \`Ratio\` (was Gauge),
\`NumberSeries\` (was Sparkline), \`PointSeries\` (was LineChart),
\`Bars\` (was BarChart), \`Image\`. Serde tag is now \`shape\` instead
of \`render\` — an honest description of what the field describes.

**Renderer trait + Registry.** Mirrors the Fetcher registry. Each
Renderer declares a name, the shapes it \`accepts\`, and renders a
\`(Body, RenderOptions)\` pair by constructing the appropriate
ratatui widget. Builtins:

- simple (Lines) — ratatui Paragraph
- bignum_tui (Lines) — tui-big-text, reads \`pixel_size\` option
- gauge (Ratio) — ratatui Gauge
- list (Entries) — ratatui Table
- sparkline (NumberSeries) — ratatui Sparkline
- chart_line (PointSeries) — ratatui Chart
- bar_chart (Bars) — ratatui BarChart
- image (Image) — ratatui-image

Lines has two registered renderers (simple + bignum_tui), proving
the shape → N renderers relationship: clock and static both emit
Lines, and the config picks which to render with.

**RenderSpec in config.** \`render = "simple"\` (short) or
\`render = { type = "bignum_tui", pixel_size = "quadrant" }\` (full,
with renderer-specific options). Replaces the dead \`render:
RenderType\` field. Absent = pick the default renderer for the
shape. Dispatch in \`render_payload\` compat-checks shape vs
renderer.accepts; mismatches and unknown names draw an inline error
rather than panicking.

**Plumbing.** \`layout::draw\` threads a \`HashMap<WidgetId,
RenderSpec>\` and a \`Registry\` through. \`runtime::run\` builds the
specs map from \`config.widgets\` and constructs a single
\`render::Registry::with_builtins\` per invocation.

\`.splashboard/config.toml\` ships as the repo's dogfood example;
\`default_config.toml\` updated to name renderers explicitly
(\`"bignum_tui"\` for the clock, \`"simple"\` for greeting).

Tests cover: short/full \`RenderSpec\` parsing, registry contains all
8 builtins, every shape has a default renderer that accepts it,
Lines has multiple renderers, bignum_tui\'s \`pixel_size\` option
parses full / quadrant / sextant / invalid.
@coderabbitai

coderabbitai Bot commented Apr 21, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

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

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 51 minutes and 46 seconds.

⌛ 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.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 87552f04-857c-4bdf-925f-de0754e8abb2

📥 Commits

Reviewing files that changed from the base of the PR and between aaf168d and 6c69197.

📒 Files selected for processing (1)
  • src/runtime.rs
📝 Walkthrough

Walkthrough

Implements a three-axis renderer architecture decoupling data shapes from renderers. Body variants renamed to shape names (Lines, Ratio, PointSeries, etc.), Serde tag changed to "shape". Introduces Renderer trait, Registry, and RenderSpec for configuration-driven renderer selection. Ports 8 existing renderers and adds 4 new ones (ascii_art, animated_typewriter, calendar, line_gauge, scatter, table). Updates stubs, config, and runtime to integrate renderer specs and registry throughout the rendering pipeline.

Changes

Cohort / File(s) Summary
Core Payload & Shape Model
src/payload.rs
Renamed Body serde tag from "render" to "shape"; replaced all 7 renderer-named variants (Bignum, Text, List, Gauge, Sparkline, LineChart, BarChart) with shape-named variants (Lines, Entries, Ratio, NumberSeries, PointSeries, Bars, Calendar); updated 8+ data struct names/fields (TextData→LinesData, ListData/ListItem→EntriesData/Entry, GaugeData→RatioData, SparklineData→NumberSeriesData, LineChartData/LineSeries→PointSeriesData/PointSeries, BarChartData→BarsData, added CalendarData/ImageData).
Renderer Registry & Trait System
src/render/mod.rs
Introduced Shape enum, Renderer trait (name/accepts/animates/render), RenderSpec (Short/Full), Registry (with_builtins/register/get), RenderOptions, and default_renderer_for(); replaced direct Body match with registry-based dispatch; added shape_of() and any_widget_animates(); updated render_payload() to accept spec/registry.
Existing Renderer Refactoring
src/render/gauge.rs, src/render/sparkline.rs, src/render/line_chart.rs, src/render/bar_chart.rs, src/render/image.rs, src/render/text.rs, src/render/list.rs
Converted 7 standalone render functions into Renderer trait implementations; each now declares Shape acceptance via accepts(), pattern-matches on new Body variant, and dispatches to internal helper.
Removed Renderer
src/render/bignum.rs
Removed entire module (was Bignum-specific render function); functionality absorbed into new ascii_art and simple renderers.
New Renderers
src/render/ascii_art.rs, src/render/animated_typewriter.rs, src/render/calendar.rs, src/render/line_gauge.rs, src/render/scatter.rs, src/render/table.rs
Added 6 new Renderer impls: ascii_art (figlet/blocks styles), animated_typewriter (progressive reveal), calendar (ratatui Monthly widget), line_gauge (compact progress bar), scatter (point plot), table (key/value with status coloring).
Config & Struct Updates
src/config.rs
Made WidgetConfig.render Option (was required RenderType enum, which was removed); added General.height for viewport sizing; default/deserialization logic updated.
Fetcher & Stub Updates
src/fetcher/clock.rs, src/fetcher/static_text.rs, src/fetcher/mod.rs, src/fetcher/stub.rs, src/cache.rs
Updated all fetchers and stubs to return new Body variants (Lines, Ratio, NumberSeries, etc.); added TrendStub (PointSeries) and TodayStub (Calendar); test helpers adapted to LinesData.
Layout & Runtime Integration
src/layout.rs, src/runtime.rs
Extended layout::draw() to accept specs/registry params and thread through recursive calls; updated render_payload() call signature; runtime now precomputes render specs, detects animation, configures viewport height, and manages multi-frame render loop with animation/wait-deadline logic.
Test Infrastructure
src/render/test_utils.rs, src/trust.rs
Added render_to_buffer_with_spec() and render_to_buffer_with_layout_and_specs() for testing; updated existing helpers to use Registry; test payloads switched to new Body variants.
Configuration & Default Settings
src/default_config.toml, .splashboard/config.toml
Updated default widget renderers (greeting: text→simple, clock: bignum→ascii_art, system: list→table); added new dogfood config with multiple renderers (ascii_art, animated_typewriter, calendar, scatter, chart, gauge, line_gauge).

Sequence Diagram

sequenceDiagram
    participant Fetcher as Fetcher
    participant Shape as Shape Detection
    participant RenderSpec as RenderSpec Config
    participant Registry as Renderer Registry
    participant Renderer as Renderer Impl
    participant Frame as Ratatui Frame

    Fetcher->>Fetcher: fetch() → Payload<br/>(Body with shape)
    
    Shape->>Shape: shape_of(body) → Shape enum
    
    RenderSpec->>RenderSpec: From config:<br/>renderer_name()
    
    Registry->>Registry: get(name) →<br/>Arc<dyn Renderer>
    
    Registry->>Renderer: Resolve renderer
    
    alt Renderer accepts shape
        Renderer->>Renderer: accepts() contains shape?
        Renderer->>Frame: render(&Body, &RenderOptions)
        Frame->>Frame: Draw widget
    else Mismatch
        Shape->>Frame: Render error placeholder
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • PR #28: Modifies the same runtime/cache/fetcher stack and async execution loop that this PR heavily refactors, indicating overlapping code-level concerns with payload types and fetcher integration.
  • PR #21: Directly refactors src/payload.rs Body structure and Serde schema that forms the foundation for this PR's shape-based redesign.
  • PR #24: Introduces and extends the layout drawing API (src/layout.rs) that this PR modifies to thread renderer specs and registry through the recursive draw flow.

Poem

🐰 Three axes dance, no more collisions—
Shapes float free from renderers' decisions!
Registry picks the perfect view,
Clock ticks bignum, figlet, or true.
Data's path and drawing's way,
Now decoupled—hip-hop-hooray! 🎨✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 36.00% 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 describes the main refactoring: introducing a data-shape Body design and Renderer registry system with 3-axis decoupling (fetcher × shape × renderer).
Linked Issues check ✅ Passed The PR fully implements all coding requirements from #32: Shape enum renaming, Renderer trait + Registry, RenderOptions, porting 8+ renderers, RenderSpec config parsing, runtime dispatch with fallback, and WidgetConfig.render now consulted at runtime.
Out of Scope Changes check ✅ Passed All changes are within scope: data-shape Body renaming, Renderer trait/Registry/RenderOptions implementation, existing renderer ports, config parsing, and runtime dispatch. New renderers (animated_typewriter, ascii_art, calendar, line_gauge, scatter, table) and stubs were added to support the core registry—properly in scope for demonstrating multi-renderer coverage.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/32-renderer-registry

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.

Two naming fixes on the initial 3-axis commit:

- \`bignum_tui\` leaked the crate name (tui-big-text) into user-
  facing config. The renderer is better framed as "ascii art" from
  the user's perspective — half-block glyphs now, figlet and other
  styles later, all under the same \`render = "ascii_art"\` entry.
  Sub-styles plug in via options (existing \`pixel_size\` stays for
  the block style; future \`style = "figlet"\` + \`font\` follow when
  figlet-rs lands).
- \`list\` suggested a TOML array or shell \`ls\`; the implementation
  is a ratatui \`Table\` with (key, value) columns. Renamed to
  \`table\` so the config word matches what you see.

File renames tracked:
- \`src/render/bignum.rs\` → \`src/render/ascii_art.rs\`
- \`src/render/list.rs\`   → \`src/render/table.rs\`

Struct renames:
- \`BignumTuiRenderer\` → \`AsciiArtRenderer\`
- \`ListRenderer\`       → \`TableRenderer\`

\`default_config.toml\` and \`.splashboard/config.toml\` updated to
match. All tests and doc comments swept.
Follow-up to the registry introduction. Pulls two more ratatui
widgets into the renderer set so the 1-shape → N-renderers story
isn't carried by Lines alone.

- \`line_gauge\` (Ratio): ratatui::LineGauge. Single-line progress
  strip for dense dashboards where the block-style \`gauge\` is too
  tall.
- \`list\` (Lines): ratatui::List. Behaviourally close to \`simple\`
  today; the distinction becomes useful once we add list-specific
  options (highlight selected item, bullet marker, scrollbar). Kept
  separate so Lines now has three registered renderers
  (simple / ascii_art / list), which makes the registry's job
  unambiguously visible in tests.

Shape → renderer coverage after this commit:

| shape          | renderers                                       |
|----------------|-------------------------------------------------|
| Lines          | simple, ascii_art, list                         |
| Ratio          | gauge, line_gauge                               |
| Entries        | table                                           |
| NumberSeries   | sparkline                                       |
| PointSeries    | chart_line                                      |
| Bars           | bar_chart                                       |
| Image          | image                                           |

Calendar, Canvas, and Scrollbar widgets from ratatui are left for
future PRs: Calendar needs a new Date shape, Canvas is low-level
enough to deserve dedicated thought, and Scrollbar is a companion
widget rather than a standalone data renderer.
Two more renderers pulled from the ratatui widget showcase instead
of being deferred to follow-ups.

- **Calendar** (new \`Calendar\` shape). Month view via ratatui's
  \`Monthly\` widget (gated behind \`widget-calendar\`). \`CalendarData\`
  carries year/month, an optional focus day (highlighted bold
  yellow), and extra event days (marked cyan). Invalid dates
  silently no-op — a hostile / buggy input must never crash the
  splash. Adds \`time\` dep (ratatui calendar specifically requires
  \`time::Date\`; chrono isn't interchangeable).
- **scatter** (PointSeries). Canvas-drawn dots-only plot, alternate
  to the Braille \`chart_line\`. Useful for showing each
  observation rather than the trend.

No fetcher produces \`Calendar\` yet — the renderer is ready for
whatever ships first (calendar widget in #14, or user plugins).

Registry now holds 11 builtin renderers across 8 shapes:

| shape          | renderers                                 |
|----------------|-------------------------------------------|
| Lines          | simple, ascii_art, list                   |
| Entries        | table                                     |
| Ratio          | gauge, line_gauge                         |
| NumberSeries   | sparkline                                 |
| PointSeries    | chart_line, scatter                       |
| Bars           | bar_chart                                 |
| Image          | image                                     |
| Calendar       | calendar                                  |
Two more Lines renderers and the runtime support they need.

**figlet.** Classic ASCII-art text via the figlet-rs crate. Paired
with \`ascii_art\` (half-block glyphs) as an alternate visual for
the same shape — users pick based on terminal density and mood.
Falls back to the raw string on conversion failure so malformed
input never blanks the slot.

**animated_typewriter.** Progressive character reveal keyed off
wall-clock time since first render (\`DEFAULT_CHARS_PER_SECOND = 40\`).
Reveal budget is clamped to the payload length — once fully typed,
it just shows the final text.

**Multi-frame wait loop.** The previous implementation called
\`draw\` once after the daemon finished, so an animated renderer
would only ever show its final frame. Rewrote the wait branch to
tick a frame every \`FRAME_TICK\` (50ms) until the daemon completes
or \`WAIT_DEADLINE\` elapses:

    loop {
        refresh_payloads(...);
        draw(...)?;
        let tick = deadline_remaining().min(FRAME_TICK);
        match tokio::time::timeout(tick, child.wait()).await {
            Ok(_) => break,  // daemon done
            Err(_) => continue,  // keep animating
        }
    }

Upshots:
- Animated renderers actually animate (during the wait window).
- Daemon cache writes now show up progressively instead of landing
  all-at-once at the end.
- Steady-state cached runs (!wait) still do exactly one draw and
  exit — zero animation overhead for the common path.

\`wait_for_daemon\` helper is gone since the inline loop subsumes it.

Shape → renderer coverage:

| shape          | renderers                                                        |
|----------------|------------------------------------------------------------------|
| Lines          | simple, ascii_art, figlet, animated_typewriter, list             |
| Entries        | table                                                            |
| Ratio          | gauge, line_gauge                                                |
| NumberSeries   | sparkline                                                        |
| PointSeries    | chart_line, scatter                                              |
| Bars           | bar_chart                                                        |
| Image          | image                                                            |
| Calendar       | calendar                                                         |

13 renderers across 8 shapes.
Backed out the standalone \`figlet\` renderer added in the previous
commit. Earlier in the design discussion I'd agreed that figlet
belongs as a style variant of \`ascii_art\` (same goal — letters
made visible — just a different visual algorithm), but then I
went and made it a peer renderer anyway. Fixing.

\`ascii_art\` now branches on \`style\`:

    render = "ascii_art"                                      # default = blocks
    render = { type = "ascii_art", style = "blocks" }         # tui-big-text blocks
    render = { type = "ascii_art", style = "blocks",
               pixel_size = "quadrant" }                      # + sub-option
    render = { type = "ascii_art", style = "figlet" }         # figlet-rs

\`RenderOptions\` picked up a \`style: Option<String>\`; \`pixel_size\`
stays and is now documented as blocks-specific. Future styles
(custom figlet fonts, animated) hang off this same renderer with
their own sub-options.

The \`figlet\` test file is deleted and its coverage moved into
\`ascii_art::tests\` as \`figlet_style_routes_through_figlet_rs\`.
Repurpose the repo-local config as a visual smoke test for the
registry: every shape and every registered renderer appears at
least once, so \`cargo run\` in this directory renders one of each
alongside the others. Real users' configs will be a fraction of
this.

To make this work:
- **Two new stub fetchers** to fill shapes we didn't have producers
  for: \`trend\` (PointSeries, Safe — hardcoded series for chart_line
  and scatter demos) and \`today\` (Calendar, Safe — reads the local
  clock for the calendar widget). Both marked Safe because the
  stubs don't actually touch network/exec; when replaced with real
  impls the classification can change.
- **Configurable viewport height**: \`general.height\` (\`Option<u16>\`,
  default 16). The showcase needs ~32 rows to fit all 13 widgets
  without clipping; the default is unchanged so nothing downstream
  shifts.

Dogfood \`.splashboard/config.toml\` covers:

| shape         | widgets (renderer)                                                 |
|---------------|---------------------------------------------------------------------|
| Lines         | greeting (simple), clock_blocks (ascii_art blocks), clock_figlet    |
|               | (ascii_art figlet), typewriter (animated_typewriter), notes (list)  |
| Entries       | system (table)                                                     |
| Ratio         | disk_gauge (gauge), disk_line (line_gauge)                         |
| NumberSeries  | commits (sparkline)                                                |
| PointSeries   | trend_line (chart_line), trend_dots (scatter)                      |
| Bars          | prs (bar_chart)                                                    |
| Calendar      | today (calendar)                                                   |

Also removed the unused \`stdout_terminal\` helper from runtime since
\`make_terminal\` now takes the viewport-lines argument and there's
no meaningful default-free form to keep.
The previous implementation tied the multi-frame render loop to the
load-wait decision: if we were going to wait for the daemon, we
looped (and animations worked); if we had cache and weren't
waiting, we drew once (and animations stayed frozen). An animated
widget flickered between "plays on first run" and "blank on warm
cache" purely based on whether the fetcher had populated cache
yet, which is a completely orthogonal axis to how the widget
should animate.

Separate the two decisions:

- **Load axis** (\`wait\`): do we block on fresh data? Still driven
  by \`--wait\`, \`general.wait_for_fresh\`, and cache emptiness.
- **Render axis** (\`animated\`): does any configured renderer need
  repeat frames? Asked via a new \`Renderer::animates()\` method
  (default \`false\`, \`AnimatedTypewriterRenderer\` overrides to
  \`true\`).

Runtime enters the multi-frame loop when either axis demands it:

    let loop_window = match (wait, animated) {
        (false, false) => None,                     // one-shot
        (false, true)  => Some(ANIMATION_WINDOW),   // 2s, just for anim
        (true, _)      => Some(WAIT_DEADLINE),      // 5s covers both
    };

\`ANIMATION_WINDOW = 2s\` — long enough for the typewriter to finish
typing, short enough that shell-startup delay is bounded. The
steady-state fast path (cached, no animations) is still a single
draw + detached daemon, no regression.

\`render::any_widget_animates(widgets, registry)\` is the compile-time-
free check the runtime uses; widgets without an explicit renderer
use shape defaults, all of which are static, so they short-circuit
to \`false\`.
After the final draw, \`println!()\` moves the cursor one line down
from wherever ratatui left it. Widgets like \`Paragraph\` (which
\`animated_typewriter\` and \`simple\` wrap) don't reset the cursor
after rendering, so on exit the cursor was wherever the last cell
was written — often in the middle of a multi-line widget. The
shell prompt then printed one line below that, inside the inline
viewport, overwriting widget content. Users saw the typewriter
animate to full text and then get clobbered as the process exited.

In the draw helper, set \`Frame::set_cursor_position\` to the bottom
row of the frame area. \`terminal.draw\` honours this hint and leaves
the cursor there on exit; \`println!()\` then moves to the row
immediately below the viewport, where the shell prompt belongs.

One place, every draw, no renderer changes.
Previous fix set the post-draw cursor to \`(0, area.height - 1)\`,
treating those as frame-relative. \`Frame::set_cursor_position\` takes
terminal-absolute coords, and the inline viewport rarely starts at
row 0 — when the shell was already partway down the terminal, the
cursor landed well above the viewport's last row. \`println!()\`
then added its newline mid-viewport, and the shell prompt
overwrote everything below that newline.

Use \`(area.x, area.y + area.height - 1)\` — the true bottom-left of
the inline region in absolute coords. The prompt now lands the row
below the viewport, regardless of where the viewport starts.

Same one-liner in the draw helper; no renderer changes.
Moving the cursor after every in-loop draw was wasted work — the
next iteration overwrites it anyway. Only the exit-time draw's
cursor matters (that's what \`println!()\` moves from).

Split into \`draw\` (plain render, used inside the loop) and
\`draw_final\` (render + park cursor at the inline area's bottom-left).
Call sites:

- fast path one-shot: \`draw_final\`
- loop body: \`draw\` per tick
- post-loop: \`draw_final\`
- daemon-spawn fallback: \`draw_final\`

No behavior change for the exit-time cursor position; just skip the
redundant positioning per frame.
\`Frame::set_cursor_position\` re-shows the cursor at the target,
which meant the caret blinked into view at the bottom-left of the
splash for a frame before the shell took over. Every intermediate
draw has the cursor hidden (ratatui's default when no cursor_pos
is set on the frame); the final move should stay consistent.

In \`draw_final\`, capture the frame's area, then call
\`Terminal::set_cursor_position\` after \`terminal.draw\` returns.
Backend-level positioning moves the cursor without toggling
visibility, so it stays hidden through the move.

Add \`finalize_splash\` helper that restores visibility via
\`Terminal::show_cursor\` and emits the trailing newline. Callers
(fast path, loop path, spawn-fail path) all go through it so the
shell prompt inherits a visible cursor.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 9

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/fetcher/clock.rs (1)

12-14: ⚠️ Potential issue | 🟡 Minor

Stale doc comment.

The doc comment still says "Emits a Bignum payload so the default layout can lean on the big-text renderer." Post-refactor the fetcher emits Body::Lines and the renderer choice is decoupled via config (render = "ascii_art"). Please update to reflect the new data-shape/renderer separation.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/fetcher/clock.rs` around lines 12 - 14, Update the stale doc comment in
src/fetcher/clock.rs: remove the line that claims the fetcher "Emits a Bignum
payload so the default layout can lean on the big-text renderer" and replace it
with a note that the fetcher now emits Body::Lines (plain text lines) and that
renderer selection is decoupled via configuration (e.g. render = "ascii_art");
adjust the summary to reflect the new data shape and config-driven renderer
choice so readers of the clock fetcher (e.g., functions/types in this file)
understand it no longer emits a Bignum payload nor picks the renderer itself.
src/render/line_chart.rs (1)

45-54: ⚠️ Potential issue | 🟡 Minor

Expand degenerate chart bounds.

A single point or flat series returns equal lower/upper bounds for an axis. Add padding so valid constant data has a drawable domain.

Proposed fix
 fn bounds(series: &[PointSeries]) -> ([f64; 2], [f64; 2]) {
@@
     let (xs, ys): (Vec<f64>, Vec<f64>) = points.into_iter().unzip();
-    ([min(&xs), max(&xs)], [min(&ys), max(&ys)])
+    (expand_bounds(min(&xs), max(&xs)), expand_bounds(min(&ys), max(&ys)))
 }
+
+fn expand_bounds(min: f64, max: f64) -> [f64; 2] {
+    if min == max {
+        [min - 1.0, max + 1.0]
+    } else {
+        [min, max]
+    }
+}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/render/line_chart.rs` around lines 45 - 54, The bounds function in
render::line_chart.rs can return identical min and max for x or y when series is
a single point or flat; update bounds (the bounds function handling PointSeries
and its returned ([f64;2], [f64;2])) to detect degenerate ranges where min ==
max and expand them by a small padding (e.g., add/subtract a fixed epsilon or a
percentage of the value or an absolute fallback like 0.5) so the returned domain
is drawable; ensure you apply this adjustment separately for the x and y ranges
after computing min(&xs)/max(&xs) and min(&ys)/max(&ys) and before returning.
🧹 Nitpick comments (2)
src/render/mod.rs (1)

196-206: any_widget_animates silently skips widgets with no explicit spec.

The comment acknowledges this is only correct while every shape's default renderer is static. If someone later changes default_renderer_for(Shape::Foo) to an animating renderer, widgets without an explicit render line for that shape will stop animating with no compile-time or test signal. Consider resolving each widget to its effective renderer name (via default_renderer_for(shape_of(...)) when w.render is None) and checking .animates() on the real renderer — or add an assertion/test that enforces the "defaults are static" invariant so future edits can't silently break it.

♻️ Alternative: check the effective renderer for each widget

Effective renderer resolution would need the cached payload or shape information per widget which isn't available at config time — so the cheaper fix is a test that locks the invariant in:

#[test]
fn every_default_renderer_is_non_animating() {
    let r = Registry::with_builtins();
    for s in [Shape::Lines, Shape::Entries, Shape::Ratio, Shape::NumberSeries,
              Shape::PointSeries, Shape::Bars, Shape::Image, Shape::Calendar] {
        let name = default_renderer_for(s);
        assert!(!r.get(name).unwrap().animates(),
            "default renderer {name} for {s:?} is animating; \
             any_widget_animates() would incorrectly skip widgets with no explicit render spec");
    }
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/render/mod.rs` around lines 196 - 206, any_widget_animates currently
skips widgets with no explicit render spec which can silently hide animating
defaults; add a unit test that pins the invariant "all default renderers are
non-animating" by constructing Registry::with_builtins(), iterating the Shape
variants (Lines, Entries, Ratio, NumberSeries, PointSeries, Bars, Image,
Calendar), resolving each default renderer via default_renderer_for(shape), and
asserting that registry.get(name).unwrap().animates() is false with a clear
failure message referencing the renderer name and Shape so future changes to
default_renderer_for or builtins will fail CI instead of silently breaking
any_widget_animates.
src/runtime.rs (1)

90-112: Frame loop re-reads every widget's cache file at 20 Hz.

refresh_payloads is called on every FRAME_TICK iteration (up to ~20×/sec for up to ANIMATION_WINDOW/WAIT_DEADLINE). For each widget that means a load_entries call that stat/reads its cache file, even when nothing has changed on disk. It's usually absorbed by the page cache, but on cold pages or slower filesystems this is avoidable churn during the splash window.

Consider refreshing opportunistically (e.g. on cache-dir change notification or by comparing cache-entry mtimes / signatures) or at a coarser cadence than FRAME_TICK while still redrawing every tick so animated renderers stay smooth.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/runtime.rs` around lines 90 - 112, The loop is calling refresh_payloads
every FRAME_TICK causing repeated load_entries/file stats; change it to refresh
opportunistically at a lower cadence or on detected file changes while keeping
draw() at FRAME_TICK. Add a last_refresh: Instant and a REFRESH_TICK (e.g.
200–500ms) and only call refresh_payloads(&cache, &registry, &fetchable, &gated,
&mut payloads) when now.duration_since(last_refresh) >= REFRESH_TICK or when a
cache-dir change/entry mtime signature differs; keep draw(&mut terminal,
&layout, &payloads, &specs, &render_registry) running every tick and update
last_refresh when refresh_payloads runs (or alternatively make load_entries in
the payload loader compare mtimes/signatures and skip re-reading unchanged
files).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In @.splashboard/config.toml:
- Around line 1-3: The comment claims every shape and renderer is exercised but
Shape::Image / renderer "image" isn't used; either add an image widget entry to
this TOML to exercise Shape::Image and renderer "image" (using an available
stub/fetcher) or edit the top comment text to remove or narrow the "every shape
and every registered renderer" claim so it accurately reflects that
Image/"image" is not covered; locate the relevant comment at the top of
.splashboard/config.toml and update it or add a new image widget stanza that
references the image renderer to resolve the mismatch.

In `@src/payload.rs`:
- Around line 21-42: The Body enum's serde tag/name change (from "render" to
"shape" and multiple variant renames) breaks deserialization of on-disk Payloads
and causes Cache::load() to silently drop stale files; either add a migration
bridge for one release by restoring backwards-compatible aliases (e.g., add
#[serde(alias = "render")] on the enum and serde aliases or renamed variants
matching the old names Text/List/Gauge/Sparkline/LineChart/BarChart/Bignum) so
old wire format still deserializes, or implement a cache-format version bump in
Cache::load() that detects the old format, deletes/stashes stale entries and
optionally logs the migration; update Cache::load() and Body (the enum and its
variant attributes) accordingly to perform one of these fixes.

In `@src/render/animated_typewriter.rs`:
- Around line 35-38: The total character budget is over-counting by adding +1
for every line (treating each line as having a trailing newline) while reveal
only emits separators between lines; in render_typewriter update the computation
of total used by chars_revealed to sum the characters of all lines and add only
the number of inter-line separators (i.e., data.lines.len().saturating_sub(1) or
max(0, data.lines.len()-1)) so the final newline isn't counted—adjust the
expression that sets total (and keep the rest of the flow using chars_revealed,
reveal, and data.lines unchanged.

In `@src/render/calendar.rs`:
- Around line 32-39: The calendar currently aborts rendering if the optional
focus `day` is invalid because `data.day` is used to build the month anchor;
change `render_calendar` to always build the month anchor using day 1 (e.g.,
call `Date::from_calendar_date(data.year, month, 1)`) so the month always
renders, and then separately validate `data.day` to create an optional focus
`Date` (use `Date::from_calendar_date` on `data.day` and only enable
highlight/focus if that succeeds). Update references in the function: replace
the current anchor creation that uses `data.day` with an anchor fixed to day 1
and add a separate `let Ok(focus) = ...` / `Option<Date>` path to handle
`data.day` validation for highlighting.

In `@src/render/gauge.rs`:
- Around line 23-25: The code calls Gauge::ratio with data.value after clamp,
but clamp doesn't prevent NaN so Gauge::ratio can panic; in render_gauge
(function render_gauge, type RatioData and its value field) and likewise in
render_line_gauge (function render_line_gauge) check value.is_finite() first and
only pass a finite value to Gauge::ratio (e.g. if value.is_finite() use
value.clamp(0.0,1.0) else use a safe default like 0.0), then proceed to build
the Gauge; ensure you apply the same finite-value guard in both render_gauge and
render_line_gauge before calling Gauge::ratio.

In `@src/render/line_gauge.rs`:
- Around line 25-31: The render_line_gauge function passes data.value straight
to LineGauge::ratio after clamp, which still allows NaN/inf to propagate; update
render_line_gauge to first normalize non-finite values from RatioData (e.g., if
!data.value.is_finite() then substitute a safe default like 0.0), then clamp the
finite value into [0.0, 1.0] and call LineGauge::ratio with that sanitized
value; keep the existing label handling (gauge.label) and frame.render_widget
calls intact.

In `@src/render/mod.rs`:
- Around line 57-82: The serde attribute #[serde(deny_unknown_fields)] on
RenderOptions conflicts with its use via #[serde(flatten)] in the untagged enum
RenderSpec and should be removed; update the RenderOptions struct to drop
deny_unknown_fields so unknown fields are ignored (matching current
comment/behavior), and add a unit test around deserializing RenderSpec::Full
with a misspelled key (e.g., "pixl_size") to assert that deserialization
succeeds and pixel_size becomes None (or change the approach to implement custom
validation if you prefer stricter behavior).

In `@src/render/scatter.rs`:
- Around line 47-56: The bounds function returns zero-width/height domains when
min == max (e.g., single-point/horizontal/vertical series); update bounds (the
bounds function operating on PointSeries, xs/ys after unzipping) to detect
degenerate axes and expand them before returning — for each axis, if min == max
compute a small padding (e.g., delta = if val == 0.0 { 1.0 } else { val.abs() *
0.01 } or a fixed 0.5) and return [min - delta, max + delta] (apply separately
for xs and ys) so constant data still renders.

In `@src/runtime.rs`:
- Around line 65-108: The loop currently breaks immediately when child.wait()
completes while wait=true, causing animations to be cut short; modify the logic
around spawn_fetch_daemon()/child and deadline so animations finish: when both
animated and wait are true, extend the deadline to max(original_deadline,
start_instant + ANIMATION_WINDOW) (use the same start instant used to compute
deadline) or, alternatively, upon Ok(_) from tokio::time::timeout(tick,
child.wait()).await do not break immediately but mark the daemon as finished and
continue the loop until the deadline expires (so draw/refresh_payloads continue
until the animation window closes); update the code paths that reference
deadline, child.wait(), and the loop break to reflect this behavior (symbols:
loop_window, ANIMATION_WINDOW, WAIT_DEADLINE, deadline, child, FRAME_TICK,
refresh_payloads, draw).

---

Outside diff comments:
In `@src/fetcher/clock.rs`:
- Around line 12-14: Update the stale doc comment in src/fetcher/clock.rs:
remove the line that claims the fetcher "Emits a Bignum payload so the default
layout can lean on the big-text renderer" and replace it with a note that the
fetcher now emits Body::Lines (plain text lines) and that renderer selection is
decoupled via configuration (e.g. render = "ascii_art"); adjust the summary to
reflect the new data shape and config-driven renderer choice so readers of the
clock fetcher (e.g., functions/types in this file) understand it no longer emits
a Bignum payload nor picks the renderer itself.

In `@src/render/line_chart.rs`:
- Around line 45-54: The bounds function in render::line_chart.rs can return
identical min and max for x or y when series is a single point or flat; update
bounds (the bounds function handling PointSeries and its returned ([f64;2],
[f64;2])) to detect degenerate ranges where min == max and expand them by a
small padding (e.g., add/subtract a fixed epsilon or a percentage of the value
or an absolute fallback like 0.5) so the returned domain is drawable; ensure you
apply this adjustment separately for the x and y ranges after computing
min(&xs)/max(&xs) and min(&ys)/max(&ys) and before returning.

---

Nitpick comments:
In `@src/render/mod.rs`:
- Around line 196-206: any_widget_animates currently skips widgets with no
explicit render spec which can silently hide animating defaults; add a unit test
that pins the invariant "all default renderers are non-animating" by
constructing Registry::with_builtins(), iterating the Shape variants (Lines,
Entries, Ratio, NumberSeries, PointSeries, Bars, Image, Calendar), resolving
each default renderer via default_renderer_for(shape), and asserting that
registry.get(name).unwrap().animates() is false with a clear failure message
referencing the renderer name and Shape so future changes to
default_renderer_for or builtins will fail CI instead of silently breaking
any_widget_animates.

In `@src/runtime.rs`:
- Around line 90-112: The loop is calling refresh_payloads every FRAME_TICK
causing repeated load_entries/file stats; change it to refresh opportunistically
at a lower cadence or on detected file changes while keeping draw() at
FRAME_TICK. Add a last_refresh: Instant and a REFRESH_TICK (e.g. 200–500ms) and
only call refresh_payloads(&cache, &registry, &fetchable, &gated, &mut payloads)
when now.duration_since(last_refresh) >= REFRESH_TICK or when a cache-dir
change/entry mtime signature differs; keep draw(&mut terminal, &layout,
&payloads, &specs, &render_registry) running every tick and update last_refresh
when refresh_payloads runs (or alternatively make load_entries in the payload
loader compare mtimes/signatures and skip re-reading unchanged files).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 373c3057-ebf6-43c0-a9d3-017bfd2fda1f

📥 Commits

Reviewing files that changed from the base of the PR and between bd8458a and aaf168d.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (29)
  • .splashboard/config.toml
  • Cargo.toml
  • src/cache.rs
  • src/config.rs
  • src/default_config.toml
  • src/fetcher/clock.rs
  • src/fetcher/mod.rs
  • src/fetcher/static_text.rs
  • src/fetcher/stub.rs
  • src/layout.rs
  • src/payload.rs
  • src/render/animated_typewriter.rs
  • src/render/ascii_art.rs
  • src/render/bar_chart.rs
  • src/render/bignum.rs
  • src/render/calendar.rs
  • src/render/gauge.rs
  • src/render/image.rs
  • src/render/line_chart.rs
  • src/render/line_gauge.rs
  • src/render/list.rs
  • src/render/mod.rs
  • src/render/scatter.rs
  • src/render/sparkline.rs
  • src/render/table.rs
  • src/render/test_utils.rs
  • src/render/text.rs
  • src/runtime.rs
  • src/trust.rs
💤 Files with no reviewable changes (1)
  • src/render/bignum.rs

Comment thread .splashboard/config.toml
Comment on lines +1 to +3
# Dogfood config for the splashboard repo itself. Every shape and every registered renderer
# appears somewhere below so `cargo run` in this directory doubles as a visual smoke test for
# the 3-axis registry. Real users' configs will be much smaller.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Include Image coverage or narrow the smoke-test claim.

This config says every shape and registered renderer appears below, but Shape::Image / renderer "image" is not exercised. Either add an image widget if a suitable stub/fetcher exists, or update the comment so the dogfood smoke test does not overstate coverage.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.splashboard/config.toml around lines 1 - 3, The comment claims every shape
and renderer is exercised but Shape::Image / renderer "image" isn't used; either
add an image widget entry to this TOML to exercise Shape::Image and renderer
"image" (using an available stub/fetcher) or edit the top comment text to remove
or narrow the "every shape and every registered renderer" claim so it accurately
reflects that Image/"image" is not covered; locate the relevant comment at the
top of .splashboard/config.toml and update it or add a new image widget stanza
that references the image renderer to resolve the mismatch.

Comment thread src/payload.rs
Comment on lines 21 to 42
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "render", content = "data", rename_all = "snake_case")]
#[serde(tag = "shape", content = "data", rename_all = "snake_case")]
pub enum Body {
Text(TextData),
List(ListData),
Gauge(GaugeData),
Sparkline(SparklineData),
LineChart(LineChartData),
BarChart(BarChartData),
Bignum(BignumData),
/// Zero or more lines of text. Used by anything that emits short strings (clock, greeting,
/// branch name) or multi-line blocks (welcome notes, todo items).
Lines(LinesData),
/// Key/value rows. Used by system info, env dumps, anything label:value shaped.
Entries(EntriesData),
/// A single 0..=1 value with an optional display label. Gauges, progress bars, donuts.
Ratio(RatioData),
/// Sequence of unsigned integers. Sparklines, histograms, bar-height sequences.
NumberSeries(NumberSeriesData),
/// Sequence of `(x, y)` points, one or more series. Line charts, scatter.
PointSeries(PointSeriesData),
/// Labeled bars. BarChart, horizontal ranking.
Bars(BarsData),
/// Path to an image on disk.
Image(ImageData),
/// A month view anchored at a specific date, optionally with highlighted events. Calendar
/// widget (and anything future that shows month-scale state) consumes this.
Calendar(CalendarData),
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm Cache::load's behavior on Payload deserialization failure and look for any
# cache-format versioning.
rg -nP -C6 '\bfn\s+(load|store)\s*\(' --type=rust -g 'src/cache*'
rg -nP -C3 '\bserde_json::from_' --type=rust -g 'src/cache*'
rg -n 'cache_version|CACHE_VERSION|schema_version' --type=rust

Repository: unhappychoice/splashboard

Length of output: 1400


Serde tag rename breaks on-disk cache wire-format.

Changing #[serde(tag = "render", ...)] → #[serde(tag = "shape", content = "data")] (plus renaming Text/List/Gauge/Sparkline/LineChart/BarChart/Bignum) means all previously-cached Payload instances fail to deserialize after upgrade. The Cache::load() method silently converts the deserialization failure to None via .ok(), treating the cache miss as if the file never existed. The widget refetches on first access—acceptable for ephemeral cache behavior, but users experience a one-off blank or slow render on upgrade.

Consider either:

  1. Bumping a cache-format version and proactively clearing stale entries on load, or
  2. Adding #[serde(alias = "render")] + variant aliases for one release as a migration bridge.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/payload.rs` around lines 21 - 42, The Body enum's serde tag/name change
(from "render" to "shape" and multiple variant renames) breaks deserialization
of on-disk Payloads and causes Cache::load() to silently drop stale files;
either add a migration bridge for one release by restoring backwards-compatible
aliases (e.g., add #[serde(alias = "render")] on the enum and serde aliases or
renamed variants matching the old names
Text/List/Gauge/Sparkline/LineChart/BarChart/Bignum) so old wire format still
deserializes, or implement a cache-format version bump in Cache::load() that
detects the old format, deletes/stashes stale entries and optionally logs the
migration; update Cache::load() and Body (the enum and its variant attributes)
accordingly to perform one of these fixes.

Comment on lines +35 to +38
fn render_typewriter(frame: &mut Frame, area: Rect, data: &LinesData) {
let total: usize = data.lines.iter().map(|l| l.chars().count() + 1).sum();
let budget = chars_revealed(total);
let revealed = reveal(&data.lines, budget);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Avoid over-counting the final newline.

total adds one character for every line, but reveal only emits separators between lines. This keeps the animation “running” one extra character after the content is already fully visible.

Proposed fix
 fn render_typewriter(frame: &mut Frame, area: Rect, data: &LinesData) {
-    let total: usize = data.lines.iter().map(|l| l.chars().count() + 1).sum();
+    let total: usize = data.lines.iter().map(|l| l.chars().count()).sum::<usize>()
+        + data.lines.len().saturating_sub(1);
     let budget = chars_revealed(total);
📝 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
fn render_typewriter(frame: &mut Frame, area: Rect, data: &LinesData) {
let total: usize = data.lines.iter().map(|l| l.chars().count() + 1).sum();
let budget = chars_revealed(total);
let revealed = reveal(&data.lines, budget);
fn render_typewriter(frame: &mut Frame, area: Rect, data: &LinesData) {
let total: usize = data.lines.iter().map(|l| l.chars().count()).sum::<usize>()
data.lines.len().saturating_sub(1);
let budget = chars_revealed(total);
let revealed = reveal(&data.lines, budget);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/render/animated_typewriter.rs` around lines 35 - 38, The total character
budget is over-counting by adding +1 for every line (treating each line as
having a trailing newline) while reveal only emits separators between lines; in
render_typewriter update the computation of total used by chars_revealed to sum
the characters of all lines and add only the number of inter-line separators
(i.e., data.lines.len().saturating_sub(1) or max(0, data.lines.len()-1)) so the
final newline isn't counted—adjust the expression that sets total (and keep the
rest of the flow using chars_revealed, reveal, and data.lines unchanged.

Comment thread src/render/calendar.rs
Comment on lines +32 to +39
fn render_calendar(frame: &mut Frame, area: Rect, data: &CalendarData) {
let Some(month) = month_from_u8(data.month) else {
return;
};
let Ok(anchor) = Date::from_calendar_date(data.year, month, data.day.unwrap_or(1).max(1))
else {
return;
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Do not let an invalid focus day blank the calendar.

day is optional focus/today metadata, but it is also used as the month anchor. If April gets day = 31, the whole widget no-ops instead of rendering April without a focus highlight. Anchor on day 1 and keep focus validation separate.

Proposed fix
-    let Ok(anchor) = Date::from_calendar_date(data.year, month, data.day.unwrap_or(1).max(1))
-    else {
+    let Ok(anchor) = Date::from_calendar_date(data.year, month, 1) else {
         return;
     };
📝 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
fn render_calendar(frame: &mut Frame, area: Rect, data: &CalendarData) {
let Some(month) = month_from_u8(data.month) else {
return;
};
let Ok(anchor) = Date::from_calendar_date(data.year, month, data.day.unwrap_or(1).max(1))
else {
return;
};
fn render_calendar(frame: &mut Frame, area: Rect, data: &CalendarData) {
let Some(month) = month_from_u8(data.month) else {
return;
};
let Ok(anchor) = Date::from_calendar_date(data.year, month, 1) else {
return;
};
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/render/calendar.rs` around lines 32 - 39, The calendar currently aborts
rendering if the optional focus `day` is invalid because `data.day` is used to
build the month anchor; change `render_calendar` to always build the month
anchor using day 1 (e.g., call `Date::from_calendar_date(data.year, month, 1)`)
so the month always renders, and then separately validate `data.day` to create
an optional focus `Date` (use `Date::from_calendar_date` on `data.day` and only
enable highlight/focus if that succeeds). Update references in the function:
replace the current anchor creation that uses `data.day` with an anchor fixed to
day 1 and add a separate `let Ok(focus) = ...` / `Option<Date>` path to handle
`data.day` validation for highlighting.

Comment thread src/render/gauge.rs
Comment on lines +23 to 25
fn render_gauge(frame: &mut Frame, area: Rect, data: &RatioData) {
let ratio = data.value.clamp(0.0, 1.0);
let mut gauge = Gauge::default().ratio(ratio);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# First, check the actual code in gauge.rs
cat -n src/render/gauge.rs | head -40

Repository: unhappychoice/splashboard

Length of output: 1393


🏁 Script executed:

# Check if RatioData is defined in this file or elsewhere
fd -t f '\.rs$' -x rg -l 'RatioData' {}

Repository: unhappychoice/splashboard

Length of output: 156


🏁 Script executed:

# Verify f64::clamp behavior with NaN using a simple Rust test
python3 << 'EOF'
# f64::clamp in Rust - let's document expected behavior
# According to Rust standard library:
# - clamp(min, max) returns val if min <= val <= max
# - Otherwise returns min or max accordingly
# - For NaN: any comparison with NaN returns false
# - So NaN.clamp(0.0, 1.0) would return NaN (not clamped)

print("f64::clamp behavior with NaN:")
print("- NaN < 0.0 = False")
print("- NaN > 1.0 = False")
print("- NaN == NaN = False")
print("- Therefore: NaN.clamp(0.0, 1.0) = NaN (passes through)")
EOF

Repository: unhappychoice/splashboard

Length of output: 215


🏁 Script executed:

# Check ratatui source or documentation references
rg -A5 'Gauge' src/render/gauge.rs | head -30

Repository: unhappychoice/splashboard

Length of output: 562


🏁 Script executed:

# Check RatioData definition
rg -A10 'struct RatioData' src/

Repository: unhappychoice/splashboard

Length of output: 491


🏁 Script executed:

# Check line_gauge.rs for similar patterns
cat -n src/render/line_gauge.rs | head -50

Repository: unhappychoice/splashboard

Length of output: 1909


🏁 Script executed:

# Search for test cases with NaN
rg 'nan|NaN' src/ -i

Repository: unhappychoice/splashboard

Length of output: 51


🏁 Script executed:

# Check if there are any validation functions for ratio values
rg -B2 -A2 'ratio.*value|value.*ratio' src/ -i

Repository: unhappychoice/splashboard

Length of output: 709


🏁 Script executed:

# Check which version of ratatui is used
cat Cargo.toml | rg 'ratatui'

Repository: unhappychoice/splashboard

Length of output: 216


🏁 Script executed:

# Check Cargo.lock for ratatui version
rg 'name = "ratatui"' Cargo.lock -A5

Repository: unhappychoice/splashboard

Length of output: 277


🏁 Script executed:

# Check if there's documentation or comments about valid ratio ranges
rg 'ratio|Gauge' src/ -B2 -A2 | head -50

Repository: unhappychoice/splashboard

Length of output: 2588


🏁 Script executed:

# Let me search more specifically for ratatui documentation and behavior
# Check if there's any test that might use invalid ratio values
rg -A10 'render_gauge|render_line_gauge' src/render/gauge.rs src/render/line_gauge.rs | grep -A15 '#\[test\]'

Repository: unhappychoice/splashboard

Length of output: 51


🏁 Script executed:

# Let's look at the full test section in gauge.rs
sed -n '32,100p' src/render/gauge.rs

Repository: unhappychoice/splashboard

Length of output: 819


🌐 Web query:

ratatui 0.29.0 Gauge::ratio panic behavior specification

💡 Result:

In ratatui 0.29.0, the Gauge::ratio method panics if the provided ratio is not within the closed interval [0.0, 1.0]. The method uses an assert! macro with the condition (0.0..=1.0).contains(&ratio) and the message "Ratio should be between 0 and 1 inclusively." This behavior is explicitly documented in the Rust API docs and source code for the Gauge widget. The render method does not panic based on ratio; tests confirm rendering works even with invalid ratios or small buffers as long as the gauge is constructed. Panics occur only during gauge construction via ratio or percent (which converts to ratio/100.0). This specification has been consistent across recent versions including 0.29.0, with no changes noted in the v0.29.0 changelog.

Citations:


Guard NaN before calling Gauge::ratio.

clamp() handles out-of-range finite values, but NaN can still flow into Gauge::ratio, which panics when the ratio is not in 0.0..=1.0. This affects both gauge.rs and line_gauge.rs. Add a finite-value check before rendering.

Proposed fix for gauge.rs
 fn render_gauge(frame: &mut Frame, area: Rect, data: &RatioData) {
-    let ratio = data.value.clamp(0.0, 1.0);
+    let ratio = if data.value.is_finite() {
+        data.value.clamp(0.0, 1.0)
+    } else {
+        0.0
+    };
     let mut gauge = Gauge::default().ratio(ratio);

Apply the same fix to render_line_gauge in src/render/line_gauge.rs:26.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/render/gauge.rs` around lines 23 - 25, The code calls Gauge::ratio with
data.value after clamp, but clamp doesn't prevent NaN so Gauge::ratio can panic;
in render_gauge (function render_gauge, type RatioData and its value field) and
likewise in render_line_gauge (function render_line_gauge) check
value.is_finite() first and only pass a finite value to Gauge::ratio (e.g. if
value.is_finite() use value.clamp(0.0,1.0) else use a safe default like 0.0),
then proceed to build the Gauge; ensure you apply the same finite-value guard in
both render_gauge and render_line_gauge before calling Gauge::ratio.

Comment thread src/render/line_gauge.rs
Comment on lines +25 to +31
fn render_line_gauge(frame: &mut Frame, area: Rect, data: &RatioData) {
let ratio = data.value.clamp(0.0, 1.0);
let mut gauge = LineGauge::default().ratio(ratio);
if let Some(label) = &data.label {
gauge = gauge.label(label.clone());
}
frame.render_widget(gauge, area);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🌐 Web query:

ratatui 0.29 LineGauge::ratio behavior when ratio is NaN or outside 0.0..=1.0

💡 Result:

In ratatui 0.29, LineGauge::ratio(f64) panics at construction if the ratio is outside 0.0..=1.0 (inclusive). NaN also triggers the panic because !(0.0 <= NaN <= 1.0) is true in Rust. If a LineGauge with invalid ratio is somehow constructed (e.g., default ratio=0.0 or via public fields if accessible), the render method likely uses the raw self.ratio in a calculation like filled_width = (area.width as f64 * self.ratio) as usize for determining filled/unfilled segment lengths. For ratio >1.0, it would fill beyond the width (clipped to width). For ratio <0.0, filled_width=0. For NaN, filled_width=NaN coerced to 0 as usize (since NaN as usize is 0 in Rust), rendering as fully unfilled.

Citations:


🏁 Script executed:

# Find and check ratatui version
fd -name "Cargo.toml" -type f | head -5 | xargs grep -l "ratatui" | xargs cat | grep -A 2 "ratatui"

Repository: unhappychoice/splashboard

Length of output: 299


🏁 Script executed:

# Read the current state of src/render/line_gauge.rs
cat -n src/render/line_gauge.rs | head -40

Repository: unhappychoice/splashboard

Length of output: 1573


🏁 Script executed:

# Verify f64::clamp behavior with NaN
python3 << 'EOF'
# Simulate Rust's f64::clamp behavior with NaN
import math

# NaN comparison behavior
nan = float('nan')
print(f"NaN clamped [0.0, 1.0]:")
print(f"  nan < 0.0: {nan < 0.0}")
print(f"  nan > 1.0: {nan > 1.0}")
print(f"  0.0 <= nan <= 1.0: {0.0 <= nan <= 1.0}")
print(f"  Result of clamp(nan, 0.0, 1.0): {max(0.0, min(nan, 1.0))}")
print(f"  Is result NaN: {math.isnan(max(0.0, min(nan, 1.0)))}")

# Infinity behavior
inf = float('inf')
ninf = float('-inf')
print(f"\nInfinity clamped [0.0, 1.0]:")
print(f"  inf clamped: {max(0.0, min(inf, 1.0))}")
print(f"  -inf clamped: {max(0.0, min(ninf, 1.0))}")

# Test is_finite equivalent (in Python, use math.isfinite)
print(f"\nis_finite checks:")
print(f"  nan is_finite: {math.isfinite(nan)}")
print(f"  inf is_finite: {math.isfinite(inf)}")
print(f"  1.0 is_finite: {math.isfinite(1.0)}")
EOF

Repository: unhappychoice/splashboard

Length of output: 374


🏁 Script executed:

# Get Cargo.toml content to find ratatui version
find . -name "Cargo.toml" -type f -exec grep -l "ratatui" {} \;

Repository: unhappychoice/splashboard

Length of output: 81


🏁 Script executed:

# Read the Cargo.toml file(s) to check ratatui version
find . -name "Cargo.toml" -type f | head -1 | xargs cat | grep -A 5 -B 5 ratatui

Repository: unhappychoice/splashboard

Length of output: 990


🌐 Web query:

Rust f64::clamp behavior with NaN documentation

💡 Result:

The Rust f64::clamp(self, min: f64, max: f64) method restricts a value to the interval [min, max] unless the input self is NaN, in which case it returns NaN. This behavior is explicitly documented in the official Rust standard library documentation: "Note that this function returns NaN if the initial value was NaN as well." The documentation also notes that if the result is zero and there are signed zeros among the inputs, the sign may be non-deterministic. This NaN-propagating behavior aligns with IEEE 754 conventions for many floating-point operations and was designed to be implementable efficiently using max and min instructions (e.g., min(max(self, min), max)), which propagate NaN from self.

Citations:


🌐 Web query:

ratatui LineGauge ratio method panic condition NaN infinite values

💡 Result:

The LineGauge::ratio(f64) method in ratatui panics if the provided ratio is not in the range [0.0, 1.0] inclusive. This is explicitly documented in the official API docs and source code. NaN and infinite values will trigger this panic because they fail the range check (0.0..=1.0).contains(&ratio), as NaN compares false to any value and infinities are outside [0,1]. There are no documented panics in the render method for LineGauge related to ratio values (assuming ratio was set validly via ratio without prior panic). Examples and source snippets show safe usage with values like 0.4 or 0.42, and default ratio is 0.0. No GitHub issues found specifically about LineGauge panicking on NaN/infinite during render.

Citations:


Handle NaN and infinite values before calling LineGauge::ratio.

clamp propagates NaN (per IEEE 754 conventions), so a non-finite ratio will pass through to LineGauge::ratio(), which panics if the ratio is outside [0.0, 1.0]. A bad fetcher/plugin can trigger this panic. Normalize non-finite values before clamping.

Proposed fix
 fn render_line_gauge(frame: &mut Frame, area: Rect, data: &RatioData) {
-    let ratio = data.value.clamp(0.0, 1.0);
+    let ratio = if data.value.is_finite() {
+        data.value.clamp(0.0, 1.0)
+    } else {
+        0.0
+    };
     let mut gauge = LineGauge::default().ratio(ratio);
📝 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
fn render_line_gauge(frame: &mut Frame, area: Rect, data: &RatioData) {
let ratio = data.value.clamp(0.0, 1.0);
let mut gauge = LineGauge::default().ratio(ratio);
if let Some(label) = &data.label {
gauge = gauge.label(label.clone());
}
frame.render_widget(gauge, area);
fn render_line_gauge(frame: &mut Frame, area: Rect, data: &RatioData) {
let ratio = if data.value.is_finite() {
data.value.clamp(0.0, 1.0)
} else {
0.0
};
let mut gauge = LineGauge::default().ratio(ratio);
if let Some(label) = &data.label {
gauge = gauge.label(label.clone());
}
frame.render_widget(gauge, area);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/render/line_gauge.rs` around lines 25 - 31, The render_line_gauge
function passes data.value straight to LineGauge::ratio after clamp, which still
allows NaN/inf to propagate; update render_line_gauge to first normalize
non-finite values from RatioData (e.g., if !data.value.is_finite() then
substitute a safe default like 0.0), then clamp the finite value into [0.0, 1.0]
and call LineGauge::ratio with that sanitized value; keep the existing label
handling (gauge.label) and frame.render_widget calls intact.

Comment thread src/render/mod.rs
Comment on lines +57 to +82
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RenderOptions {
/// ascii_art: "blocks" (default, tui-big-text) | "figlet" (figlet-rs).
#[serde(default)]
pub style: Option<String>,
/// ascii_art blocks style: "full" | "quadrant" | "sextant". None = adaptive (pick by area
/// height). Ignored by other styles.
#[serde(default)]
pub pixel_size: Option<String>,
}

/// What the TOML accepts for `render`. Short form `render = "simple"` uses defaults; long form
/// `render = { type = "ascii_art", pixel_size = "quadrant" }` carries options. Absence means
/// "use the default renderer for this shape".
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum RenderSpec {
Short(String),
Full {
#[serde(rename = "type")]
type_name: String,
#[serde(flatten)]
options: RenderOptions,
},
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🌐 Web query:

Does serde #[serde(deny_unknown_fields)]work when the struct is used through#[serde(flatten)] inside an untagged enum variant? What is the documented behavior?

💡 Result:

No, serde #[serde(deny_unknown_fields)] does not reliably work when the struct is used through #[serde(flatten)] inside an untagged enum variant. The official Serde documentation explicitly states that deny_unknown_fields is not supported in combination with flatten, neither on the outer struct nor on the flattened field. This applies directly to the scenario where a struct with deny_unknown_fields is flattened into an untagged enum variant, as the flattened field is the untagged enum containing the struct variant. Specific issues confirm problematic behavior: in GitHub issue #1600, applying deny_unknown_fields to an outer struct that flattens an untagged enum fails deserialization even without unknown fields. Nested flattens with deny_unknown_fields also fail (issue #1547). While workarounds exist like moving deny_unknown_fields to inner structs, the documented behavior is that the combination is unsupported and fragile, potentially failing in complex cases.

Citations:


🏁 Script executed:

cat -n src/render/mod.rs | head -100

Repository: unhappychoice/splashboard

Length of output: 3625


🏁 Script executed:

# Search for all uses of RenderOptions and RenderSpec to confirm the flatten usage
rg -n "RenderOptions|RenderSpec" src/render/mod.rs -A 2 -B 2

Repository: unhappychoice/splashboard

Length of output: 1494


🏁 Script executed:

# Look for tests related to RenderOptions or RenderSpec
fd -e rs -path "*/test*" -o -path "*/tests/*" | xargs rg -l "RenderOptions|RenderSpec" 2>/dev/null || find . -name "*test*.rs" | xargs rg -l "RenderOptions|RenderSpec" 2>/dev/null

Repository: unhappychoice/splashboard

Length of output: 639


🏁 Script executed:

# Check if there are any integration or unit tests for render deserialization
rg -n "render.*=.*{" --type rust -A 5 | grep -E "(test|mod test)" -B 10 -A 10 | head -50

Repository: unhappychoice/splashboard

Length of output: 156


🏁 Script executed:

# Look at test_utils.rs
cat -n src/render/test_utils.rs

Repository: unhappychoice/splashboard

Length of output: 2631


🏁 Script executed:

# Search for tests that use RenderSpec with various field combinations
rg -n "RenderSpec|render.*=" src/ --type rust -B 2 -A 5 | grep -E "test|#\[test\]" -B 5 -A 10 | head -80

Repository: unhappychoice/splashboard

Length of output: 4423


🏁 Script executed:

# Check config.rs for how RenderSpec is used in deserialization
rg -n "RenderSpec|RenderOptions" src/config.rs -B 3 -A 3

Repository: unhappychoice/splashboard

Length of output: 576


🏁 Script executed:

# Get the rest of the test in src/render/mod.rs
sed -n '216,280p' src/render/mod.rs

Repository: unhappychoice/splashboard

Length of output: 1958


🏁 Script executed:

# Check if there are any tests that try to deserialize with unknown fields in RenderSpec
rg -n "unknown|typo|invalid" src/render/mod.rs -B 5 -A 5

Repository: unhappychoice/splashboard

Length of output: 1518


🏁 Script executed:

# Let's run a quick test to see what actually happens with deny_unknown_fields + flatten
cat > /tmp/test_serde.rs << 'EOF'
use serde::{Deserialize};

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Options {
    pub known: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum Spec {
    Short(String),
    Full {
        #[serde(rename = "type")]
        type_name: String,
        #[serde(flatten)]
        options: Options,
    },
}

fn main() {
    // Test 1: valid field
    match serde_json::from_str::<Spec>(r#"{"type": "test", "known": "value"}"#) {
        Ok(s) => println!("Test 1 (valid): {:?}", s),
        Err(e) => println!("Test 1 error: {}", e),
    }
    
    // Test 2: unknown field (should fail with deny_unknown_fields, but might not)
    match serde_json::from_str::<Spec>(r#"{"type": "test", "unknown_field": "value"}"#) {
        Ok(s) => println!("Test 2 (unknown): PARSED WITHOUT ERROR: {:?}", s),
        Err(e) => println!("Test 2 error (expected): {}", e),
    }
    
    // Test 3: both known and unknown
    match serde_json::from_str::<Spec>(r#"{"type": "test", "known": "k", "unknown": "u"}"#) {
        Ok(s) => println!("Test 3 (mixed): PARSED WITHOUT ERROR: {:?}", s),
        Err(e) => println!("Test 3 error (expected): {}", e),
    }
}
EOF

# Create Cargo.toml for the test
cat > /tmp/Cargo.toml << 'EOF'
[package]
name = "test"
version = "0.1.0"
edition = "2021"

[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
EOF

cd /tmp && rustc --edition 2021 -L /usr/local/cargo/registry/cache/*/serde* -L /usr/local/cargo/registry/cache/*/serde_json* test_serde.rs -o test_serde 2>&1 || echo "Rust not available in sandbox"

Repository: unhappychoice/splashboard

Length of output: 143


🏁 Script executed:

# Let's check what the remaining tests in src/render/mod.rs actually test
sed -n '220,300p' src/render/mod.rs

Repository: unhappychoice/splashboard

Length of output: 2386


🏁 Script executed:

# Check if there are any more tests after line 280 that test error cases
sed -n '280,320p' src/render/mod.rs

Repository: unhappychoice/splashboard

Length of output: 597


🏁 Script executed:

# Search for any integration tests that might test TOML parsing with unknown fields
find . -name "*.rs" -type f | xargs rg -l "deny_unknown_fields|unknown.*field" 2>/dev/null | head -20

Repository: unhappychoice/splashboard

Length of output: 88


🏁 Script executed:

# Check if there are any other files that use RenderOptions with deny_unknown_fields
rg -n "RenderOptions" src/ --type rust -B 5 -A 5

Repository: unhappychoice/splashboard

Length of output: 19253


🏁 Script executed:

# Look at the comment at lines 54-56 more carefully - does it say "others are ignored"?
sed -n '54,56p' src/render/mod.rs

Repository: unhappychoice/splashboard

Length of output: 313


deny_unknown_fields on RenderOptions is ineffective and contradicts code intent because it is consumed via #[serde(flatten)] in an untagged enum.

Serde explicitly documents this combination as unsupported: "flatten is not supported in combination with structs that use deny_unknown_fields. Neither the outer nor inner flattened struct should use that attribute." When used this way, the attribute is either silently ignored or causes unpredictable deserialization failures. This directly contradicts the comment at line 54-56 which states "others are ignored"—with deny_unknown_fields, unknown fields should be rejected, not ignored.

Practical consequence: render = { type = "ascii_art", pixl_size = "quadrant" } (typo) deserializes successfully with pixel_size = None, silently swallowing the user's intent rather than flagging a configuration error.

Two practical options:

  1. Drop deny_unknown_fields to align code with the stated intent (unknown fields are ignored). This is honest but loses validation.
  2. Custom-deserialize RenderSpec::Full to validate options against a renderer-declared schema (stricter but more work).

At minimum, add a test for unknown field handling so future serde versions don't silently break this behavior.

🔧 Minimal fix (remove the unsupported attr)
 #[derive(Debug, Clone, Default, Deserialize)]
-#[serde(deny_unknown_fields)]
 pub struct RenderOptions {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/render/mod.rs` around lines 57 - 82, The serde attribute
#[serde(deny_unknown_fields)] on RenderOptions conflicts with its use via
#[serde(flatten)] in the untagged enum RenderSpec and should be removed; update
the RenderOptions struct to drop deny_unknown_fields so unknown fields are
ignored (matching current comment/behavior), and add a unit test around
deserializing RenderSpec::Full with a misspelled key (e.g., "pixl_size") to
assert that deserialization succeeds and pixel_size becomes None (or change the
approach to implement custom validation if you prefer stricter behavior).

Comment thread src/render/scatter.rs
Comment on lines +47 to +56
fn bounds(series: &[PointSeries]) -> ([f64; 2], [f64; 2]) {
let points: Vec<(f64, f64)> = series
.iter()
.flat_map(|s| s.points.iter().copied())
.collect();
if points.is_empty() {
return ([0.0, 1.0], [0.0, 1.0]);
}
let (xs, ys): (Vec<f64>, Vec<f64>) = points.into_iter().unzip();
([min(&xs), max(&xs)], [min(&ys), max(&ys)])

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Expand degenerate scatter bounds.

For a single point, horizontal series, or vertical series, min == max, so this returns a zero-width/zero-height domain. Pad that axis before passing it to the canvas so valid constant data still renders.

Proposed fix
 fn bounds(series: &[PointSeries]) -> ([f64; 2], [f64; 2]) {
@@
     let (xs, ys): (Vec<f64>, Vec<f64>) = points.into_iter().unzip();
-    ([min(&xs), max(&xs)], [min(&ys), max(&ys)])
+    (expand_bounds(min(&xs), max(&xs)), expand_bounds(min(&ys), max(&ys)))
 }
+
+fn expand_bounds(min: f64, max: f64) -> [f64; 2] {
+    if min == max {
+        [min - 1.0, max + 1.0]
+    } else {
+        [min, max]
+    }
+}
📝 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
fn bounds(series: &[PointSeries]) -> ([f64; 2], [f64; 2]) {
let points: Vec<(f64, f64)> = series
.iter()
.flat_map(|s| s.points.iter().copied())
.collect();
if points.is_empty() {
return ([0.0, 1.0], [0.0, 1.0]);
}
let (xs, ys): (Vec<f64>, Vec<f64>) = points.into_iter().unzip();
([min(&xs), max(&xs)], [min(&ys), max(&ys)])
fn bounds(series: &[PointSeries]) -> ([f64; 2], [f64; 2]) {
let points: Vec<(f64, f64)> = series
.iter()
.flat_map(|s| s.points.iter().copied())
.collect();
if points.is_empty() {
return ([0.0, 1.0], [0.0, 1.0]);
}
let (xs, ys): (Vec<f64>, Vec<f64>) = points.into_iter().unzip();
(expand_bounds(min(&xs), max(&xs)), expand_bounds(min(&ys), max(&ys)))
}
fn expand_bounds(min: f64, max: f64) -> [f64; 2] {
if min == max {
[min - 1.0, max + 1.0]
} else {
[min, max]
}
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/render/scatter.rs` around lines 47 - 56, The bounds function returns
zero-width/height domains when min == max (e.g.,
single-point/horizontal/vertical series); update bounds (the bounds function
operating on PointSeries, xs/ys after unzipping) to detect degenerate axes and
expand them before returning — for each axis, if min == max compute a small
padding (e.g., delta = if val == 0.0 { 1.0 } else { val.abs() * 0.01 } or a
fixed 0.5) and return [min - delta, max + delta] (apply separately for xs and
ys) so constant data still renders.

Comment thread src/runtime.rs
Comment on lines +65 to +108
let loop_window = match (wait, animated) {
(false, false) => None,
(false, true) => Some(ANIMATION_WINDOW),
(true, _) => Some(WAIT_DEADLINE),
};

// Cache-first: unless we're waiting, paint what we have from disk (plus trust placeholders)
// immediately so the shell prompt is never blocked on fetch I/O.
let drew_cached = !wait && !payloads.is_empty();
if drew_cached {
draw(&mut terminal, &layout, &payloads)?;
let viewport_lines = config.general.height.unwrap_or(DEFAULT_VIEWPORT_LINES);
let backend = CrosstermBackend::new(stdout());
let mut terminal = make_terminal(backend, viewport_lines)?;

// Cache-first one-shot: no looping needed, paint what we have and exit.
if loop_window.is_none() {
draw(&mut terminal, &layout, &payloads, &specs, &render_registry)?;
let _ = daemon::spawn_fetch_daemon(config_ident.map(|(p, _)| p));
println!();
return Ok(());
}

let window = loop_window.unwrap();
match daemon::spawn_fetch_daemon(config_ident.map(|(p, _)| p)) {
Ok(child) => {
if wait {
// Block on the daemon (with a hard ceiling) and then draw with whatever it
// managed to write before the deadline.
let _ = wait_for_daemon(child, WAIT_DEADLINE).await;
Ok(mut child) => {
// Multi-frame loop: ticks the frame every FRAME_TICK so animated renderers can
// animate; picks up daemon-written cache entries as they land; stops when the
// daemon finishes (if we were waiting for it) or the window expires.
let deadline = std::time::Instant::now() + window;
loop {
refresh_payloads(&cache, &registry, &fetchable, &gated, &mut payloads);
draw(&mut terminal, &layout, &payloads)?;
draw(&mut terminal, &layout, &payloads, &specs, &render_registry)?;
let remaining = deadline.saturating_duration_since(std::time::Instant::now());
if remaining.is_zero() {
if wait {
let _ = child.start_kill();
}
break;
}
let tick = remaining.min(FRAME_TICK);
if wait {
match tokio::time::timeout(tick, child.wait()).await {
Ok(_) => break,
Err(_) => continue,
}
} else {
tokio::time::sleep(tick).await;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Animation may be cut short when wait=true.

When both wait and animated are true, the loop exits as soon as child.wait() returns (Line 103). If the daemon finishes before the animation completes, the partially-rendered animation (e.g. animated_typewriter mid-type) is what the user sees before the final draw on Line 111. If this is intentional (wait-for-data dominates animation), ignore — otherwise consider deadline = max(fetch_deadline, start + ANIMATION_WINDOW) or continuing the loop after child exit until the animation window closes.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/runtime.rs` around lines 65 - 108, The loop currently breaks immediately
when child.wait() completes while wait=true, causing animations to be cut short;
modify the logic around spawn_fetch_daemon()/child and deadline so animations
finish: when both animated and wait are true, extend the deadline to
max(original_deadline, start_instant + ANIMATION_WINDOW) (use the same start
instant used to compute deadline) or, alternatively, upon Ok(_) from
tokio::time::timeout(tick, child.wait()).await do not break immediately but mark
the daemon as finished and continue the loop until the deadline expires (so
draw/refresh_payloads continue until the animation window closes); update the
code paths that reference deadline, child.wait(), and the loop break to reflect
this behavior (symbols: loop_window, ANIMATION_WINDOW, WAIT_DEADLINE, deadline,
child, FRAME_TICK, refresh_payloads, draw).

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: renderer registry + data-shape / renderer decoupling (3-axis)

1 participant