Skip to content

refactor(render): split RenderOptions into common + per-renderer specific structs - #147

Merged
unhappychoice merged 1 commit into
mainfrom
refactor/render-options-split
Apr 26, 2026
Merged

unhappychoice merged 1 commit into
mainfrom
refactor/render-options-split

Conversation

@unhappychoice

@unhappychoice unhappychoice commented Apr 26, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • RenderOptions keeps only the 12 fields used by ≥2 renderers across families (align, style, color, label, padding, bullet, max_items, tone, value_format, duration_ms, axes); the previous 40+ flat-bag fields collapse into a flatten'd raw: toml::Table. Each renderer now owns a private Options { #[serde(deny_unknown_fields)] } and reads it via opts.parse_specific::<Options>(), mirroring the fetcher side (FetchContext.options → per-fetcher struct).
  • Adds with_extra / without_extra builder methods for animation wrappers (animated_postfx / animated_boot / animated_scanlines / animated_splitflap / animated_wave) and tests that previously poked private fields via FRU. extra_str / extra_string_array give the xtask crate a serde-free way to peek at single keys without growing a new dependency.
  • Migrates every existing renderer (text_ascii, chart_bar/histogram/pie/scatter, gauge_circle/segment, grid_calendar/heatmap/table, list_timeline, status_badge, media_image, all animated_*) plus the preview / snapshot helpers in src/install/preview.rs and xtask/src/dashboard_snapshot.rs. No behavioural change — typo detection on per-renderer keys now happens via each Options::deny_unknown_fields instead of one struct-wide attribute.

Test plan

  • cargo fmt --all -- --check
  • cargo clippy --all-targets --workspace -- -D warnings
  • cargo test --workspace (615 + 12 + 2 passing)
  • cargo run --bin splashboard — sanity-check that an existing dashboard still renders unchanged

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Refactor
    • Restructured internal renderer option handling architecture to use typed configuration structs for improved validation across all renderer modules.

…ific structs

Mirrors the fetcher pattern (`FetchContext.options: Option<toml::Value>` → typed
per-fetcher struct) on the renderer side. `RenderOptions` keeps the cross-cutting
fields used by ≥2 renderers across families (`align`, `style`, `color`, `label`,
`padding`, `bullet`, `max_items`, `tone`, `value_format`, `duration_ms`, `axes`)
and collects everything else into a flatten'd `raw: toml::Table`. Each renderer
now declares its own `Options { #[serde(deny_unknown_fields)] }` and reads it via
`opts.parse_specific::<Options>()`, so renderer-specific knobs live next to the
code that consumes them instead of bloating the central bag.

Adds `with_extra` / `without_extra` builder helpers for tests and animation
wrappers that need to forward a modified options bag, plus thin `extra_str` /
`extra_string_array` accessors used by xtask preview helpers that don't pull in
serde directly.

Migrates every existing renderer (text_ascii / chart_* / gauge_* / grid_* /
list_timeline / status_badge / media_image / animated_*) and the preview /
snapshot helpers in `install` and `xtask`.

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

coderabbitai Bot commented Apr 26, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

RenderOptions is refactored from a flat structure containing many renderer-specific fields into a split model where common fields remain typed and renderer-specific keys are collected into a raw: toml::Table. New helper methods enable runtime decoding of renderer-specific options, and 20+ renderers are updated to parse their configuration via the new parse_specific() method instead of accessing direct fields.

Changes

Cohort / File(s) Summary
Core RenderOptions Architecture
src/render/mod.rs
Splits RenderOptions into typed common fields and raw: toml::Table for renderer-specific keys. Adds parse_specific(), with_extra(), without_extra(), extra_str(), and extra_string_array() methods for runtime option parsing. Removes 30+ renderer-specific typed fields.
Animated Wrappers
src/render/animated_boot.rs, animated_figlet_morph.rs, animated_postfx.rs, animated_scanlines.rs, animated_splitflap.rs, animated_wave.rs
All refactored to parse renderer-specific Options structs via parse_specific(). Inner renderer resolution, boot lines, font sequences, and effects now read from parsed options. inner_options helpers updated to use .without_extra(...) chaining instead of field nullification.
Chart Renderers
src/render/chart_bar.rs, chart_histogram.rs, chart_pie.rs, chart_scatter.rs
Updated to derive configuration values (max_bars, horizontal, axis_labels, bins, legend, donut, marker) from dedicated serde-deserialized Options structs via parse_specific() instead of direct field access.
Grid & Layout Renderers
src/render/grid_calendar.rs, grid_heatmap.rs, grid_table.rs
Now parse and validate renderer-specific options through typed Options structs. Cell character selection, layout modes, and column alignment read from parsed options with unknown-field rejection.
Gauge & Status Renderers
src/render/gauge_circle.rs, gauge_segment.rs, status_badge.rs
Updated to parse Options structs and validate reserved fields via parse_specific(). Segment count, ring thickness, label position, and shape selection now read from parsed options.
Text & Media Renderers
src/render/text_ascii.rs, media_image.rs, list_timeline.rs
Added Options structs for font overrides, pixel size, image fitting, dimensions, and date formatting. Option values extracted via parse_specific() instead of direct field access. Tests updated to use .with_extra(...) for per-renderer configuration.
Preview & Dashboard Tools
src/install/preview.rs, xtask/src/dashboard_snapshot.rs
Helper functions added for inner_renderer_name() and font_sequence() parsing. Deanimate logic updated to extract inner renderer names and font lists via helpers; font injection switched to .with_extra("font", ...) pattern.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🐰 Hop, hop! The options now flow through a pattern so clean—
Parse them specific, strip them with care, keep the schema quite keen!
From charts to animations, each renderer now knows:
Extra fields belong in the raw, where the config tree grows. 🌱

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 74.68% 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 pull request title accurately and specifically summarizes the main architectural change: refactoring RenderOptions into common + per-renderer specific structs, which is the core focus of this large-scale refactoring across multiple renderer modules.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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 refactor/render-options-split

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.

@codecov

codecov Bot commented Apr 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 84.33180% with 34 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.32%. Comparing base (7332af3) to head (3f84f4c).
⚠️ Report is 34 commits behind head on main.

Files with missing lines Patch % Lines
src/install/preview.rs 27.77% 13 Missing ⚠️
src/render/mod.rs 72.97% 10 Missing ⚠️
src/render/animated_boot.rs 92.59% 2 Missing ⚠️
src/render/animated_scanlines.rs 85.71% 2 Missing ⚠️
src/render/animated_splitflap.rs 80.00% 2 Missing ⚠️
src/render/animated_wave.rs 85.71% 2 Missing ⚠️
src/render/animated_figlet_morph.rs 90.90% 1 Missing ⚠️
src/render/media_image.rs 91.66% 1 Missing ⚠️
src/render/text_ascii.rs 93.33% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #147      +/-   ##
==========================================
+ Coverage   79.29%   79.32%   +0.02%     
==========================================
  Files          98       98              
  Lines       18478    18552      +74     
==========================================
+ Hits        14652    14716      +64     
- Misses       3826     3836      +10     
Files with missing lines Coverage Δ
src/render/animated_postfx.rs 95.88% <100.00%> (+0.01%) ⬆️
src/render/chart_bar.rs 95.20% <100.00%> (+0.03%) ⬆️
src/render/chart_histogram.rs 97.47% <100.00%> (+0.02%) ⬆️
src/render/chart_pie.rs 93.85% <100.00%> (+0.05%) ⬆️
src/render/chart_scatter.rs 84.31% <100.00%> (+0.15%) ⬆️
src/render/gauge_circle.rs 89.09% <100.00%> (+0.62%) ⬆️
src/render/gauge_segment.rs 96.85% <100.00%> (+0.01%) ⬆️
src/render/grid_calendar.rs 88.05% <100.00%> (+0.24%) ⬆️
src/render/grid_heatmap.rs 96.75% <100.00%> (+<0.01%) ⬆️
src/render/grid_table.rs 94.20% <100.00%> (+0.04%) ⬆️
... and 11 more

... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@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: 5

🧹 Nitpick comments (6)
src/render/grid_table.rs (1)

84-90: Minor: parameter-type asymmetry between render_rows and render_inline.

render_rows now takes &Options while render_inline still takes &RenderOptions (only to read the common align). It works, but it makes the dispatch in render (lines 84-89) read inconsistently. Either pass both opts and &specific to both helpers, or just pass &RenderOptions everywhere and let each helper call parse_specific itself when it needs renderer-specific keys. Not blocking.

♻️ Optional unification
         if let Body::Entries(d) = body {
             let specific: Options = opts.parse_specific();
             match specific.layout.as_deref() {
-                Some("inline") => render_inline(frame, area, d, opts, theme),
-                _ => render_rows(frame, area, d, &specific, theme),
+                Some("inline") => render_inline(frame, area, d, opts, theme),
+                _ => render_rows(frame, area, d, &specific, theme),
             }
         }

(Or equivalently, pass opts.align.as_deref() through Options and drop the &RenderOptions arg from render_inline.)

Also applies to: 109-115

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

In `@src/render/grid_table.rs` around lines 84 - 90, The dispatch in render uses
mixed parameter types—render_rows(&Options) vs
render_inline(&RenderOptions)—which is inconsistent; update the helper
signatures so both accept the same type: either change render_inline to take
&Options (the parsed specific) or change render_rows to take &RenderOptions and
let each helper call parse_specific() as needed; adjust all call sites
(including the other occurrences around lines 109-115) and update parameter
names in render_inline, render_rows, and any internal uses of align or specific
fields (Options, RenderOptions, parse_specific, render_inline, render_rows,
render) to match the unified signature.
src/render/chart_bar.rs (1)

14-28: LGTM — the per-renderer split is clean.

max_bars, horizontal, and bar_width move into the local Options, and stacked is correctly carved out as a forward-compat reservation (with #[allow(dead_code)] plus an inline rationale). One small note: existing tests cover max_bars via capped_bars(...) directly but never exercise the option going through parse_specific() end-to-end. If you want a tiny safety net for the new wiring, a test that drives horizontal = true or max_bars = 2 through a RenderSpec::Full would catch a future regression where the keys silently fall back to Default.

Also applies to: 100-109

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

In `@src/render/chart_bar.rs` around lines 14 - 28, Tests don't exercise the new
per-renderer Options being parsed from a RenderSpec end-to-end; add a small
unit/integration test that constructs a RenderSpec::Full containing the options
keys (e.g., "horizontal": true and "max_bars": 2 or "bar_width": N) and calls
parse_specific() to ensure the produced Options struct (and downstream behavior)
reflects those values rather than defaults. Locate the parsing path that
produces Options (the Options struct in chart_bar.rs and the parse_specific()
call site) and assert that Options.horizontal, Options.max_bars, and
Options.bar_width are set as expected when parsed through RenderSpec::Full so
future regressions are caught.
src/render/media_image.rs (1)

102-118: Optional: parse Options once and thread it through.

compute_target and render_image both call opts.parse_specific() for the same (fit, max_width, max_height) triple per draw. Mirroring the text_ascii change (parse once in render, pass &Options to helpers) would avoid the double decode and keep the two read sites in sync if Options grows.

♻️ Sketch
-fn render_image_payload(
-    frame: &mut Frame,
-    area: Rect,
-    data: &ImageData,
-    opts: &RenderOptions,
-    theme: &Theme,
-) {
-    let target = compute_target(area, opts);
-    match render_image(frame, target, &data.path, opts) {
+fn render_image_payload(
+    frame: &mut Frame,
+    area: Rect,
+    data: &ImageData,
+    opts: &RenderOptions,
+    theme: &Theme,
+) {
+    let specific: Options = opts.parse_specific();
+    let target = compute_target(area, opts, &specific);
+    match render_image(frame, target, &data.path, &specific) {

Also applies to: 130-138

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

In `@src/render/media_image.rs` around lines 102 - 118, compute_target and
render_image both call opts.parse_specific(), causing duplicate parsing; parse
the specific Options once in the caller (e.g., in render before calling
compute_target and render_image), store it in a local variable (Options) and
pass a reference (&Options) into compute_target and render_image instead of
calling parse_specific() inside them; update function signatures to accept the
&Options reference where needed (compute_target(..., opts: &RenderOptions,
specific: &Options) or compute_target(..., specific: &Options)) and remove the
internal parse_specific() calls in render_image and the other helper (also
adjust the second site mentioned around the 130-138 region), ensuring all uses
reference the single parsed Options instance.
src/install/preview.rs (1)

264-284: Use the new extra_str / extra_string_array accessors instead of ad-hoc Wrapper structs.

xtask/src/dashboard_snapshot.rs does the exact same lookup against opts.extra_str("inner") and opts.extra_string_array("font_sequence") — the helpers were added in this PR for precisely this peek-one-key use case. Aligning here removes the duplicated Wrapper boilerplate and also avoids the parse_specific + deny_unknown_fields cascade (an unknown key in raw would currently make these Wrappers parse-fail and silently drop inner / font_sequence).

♻️ Proposed simplification
-/// Pull the wrapper renderer's `inner` field out of the raw extras blob, falling back to
-/// `text_plain` so previews always have a concrete renderer to delegate to.
-fn inner_renderer_name(opts: &RenderOptions) -> String {
-    #[derive(serde::Deserialize, Default)]
-    struct Wrapper {
-        #[serde(default)]
-        inner: Option<String>,
-    }
-    let parsed: Wrapper = opts.parse_specific();
-    parsed.inner.unwrap_or_else(|| "text_plain".into())
-}
-
-fn font_sequence(opts: &RenderOptions) -> Option<Vec<String>> {
-    #[derive(serde::Deserialize, Default)]
-    struct Wrapper {
-        #[serde(default)]
-        font_sequence: Option<Vec<String>>,
-    }
-    let parsed: Wrapper = opts.parse_specific();
-    parsed.font_sequence
-}
+/// Pull the wrapper renderer's `inner` field out of the raw extras blob, falling back to
+/// `text_plain` so previews always have a concrete renderer to delegate to.
+fn inner_renderer_name(opts: &RenderOptions) -> String {
+    opts.extra_str("inner")
+        .map(String::from)
+        .unwrap_or_else(|| "text_plain".into())
+}
+
+fn font_sequence(opts: &RenderOptions) -> Option<Vec<String>> {
+    opts.extra_string_array("font_sequence")
+}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/install/preview.rs` around lines 264 - 284, Replace the ad-hoc serde
Wrapper parsing in inner_renderer_name and font_sequence with the new
RenderOptions accessors: call opts.extra_str("inner") and use its Some value or
default to "text_plain" for inner_renderer_name, and call
opts.extra_string_array("font_sequence") to return the Option<Vec<String>> for
font_sequence; this removes the Wrapper structs and avoids
parse_specific/deny_unknown_fields behavior while preserving the same return
semantics.
src/render/animated_wave.rs (1)

183-192: Fragile: inner_options strips keys that belong to other wrappers.

effect is animated_postfx, boot_lines is animated_boot, font_sequence is animated_figlet_morph. Each animated wrapper now has to know about every other wrapper's keys so the inner renderer's parse_specific (which uses deny_unknown_fields) doesn't reject them and silently drop its own config. Every new wrapper key will require an edit here and in every sibling wrapper.

Two cleaner options worth considering:

  • Centralize: a single WRAPPER_KEYS: &[&str] constant (or RenderOptions::without_wrapper_extras() helper) that every wrapper can call.
  • Or: relax the inner renderers' Options to not use deny_unknown_fields, since unknown keys can legitimately come from outer wrappers.

Either avoids the "every wrapper must enumerate every other wrapper's keys" coupling.

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

In `@src/render/animated_wave.rs` around lines 183 - 192, The current
inner_options function in animated_wave.rs enumerates other wrappers' keys
(effect, boot_lines, font_sequence) which is fragile; instead add a centralized
list or helper and use that here: create a single WRAPPER_KEYS constant (or
implement RenderOptions::without_wrapper_extras(&self)) that contains all
wrapper-specific keys, and change inner_options to clone opts and call the new
helper (e.g., opts.clone().without_extras(&WRAPPER_KEYS) or
opts.clone().without_wrapper_extras()) so wrappers no longer need to know each
other's keys and new wrapper keys only require updating the single central
list/helper.
src/render/mod.rs (1)

173-184: Consider pub(crate) or a typed builder instead of pub for raw.

The doc-comment instructs callers to go through with_extra / without_extra, but pub raw: toml::Table lets any downstream insert/remove arbitrary entries and bypass that contract. The justification ("pub so functional-record-update compiles in tests and the xtask crate") is real, but it could also be served by:

  • pub(crate) plus a re-export shim if xtask actually needs it (the new extra_str / extra_string_array already cover the snapshot's read needs), or
  • Keeping it pub but adding #[doc(hidden)] so it doesn't appear in the public API surface.

Not blocking — flagging in case the long-term plan is to keep these helpers as the only mutation path.

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

In `@src/render/mod.rs` around lines 173 - 184, The field RenderOptions::raw is
public but callers should use with_extra/without_extra; change its visibility to
pub(crate) to prevent downstream mutation (update any xtask consumers by adding
a crate-level re-export/shim if needed), or if you must keep it public for
tests/xtask, annotate it with #[doc(hidden)] and keep the existing
extra_str/extra_string_array helpers for snapshot reads; ensure code references
to raw in tests or xtask are adjusted to use the shim or remain accessible via
the intended visibility.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/render/animated_postfx.rs`:
- Around line 386-393: The test is vacuous because parse_specific::<Options>()
returns Default when unknown fields exist; instead assert against the raw blob
to ensure stripping happened: after calling the helper (e.g.
without_extra/inner_options) check inner.raw (the raw JSON/string map) does not
contain the keys "inner" and "effect" (and/or their serialized forms) and still
contains the renderer-specific key "pixel_size" so parsed_text.pixel_size
remains "quadrant"; keep the existing parse_specific checks for parsed_text but
replace or add assertions that directly inspect inner.raw to confirm "inner" and
"effect" were removed.

In `@src/render/animated_scanlines.rs`:
- Around line 183-192: The helper logic that strips wrapper-specific extra keys
is duplicated across inner_options in multiple files; create a single helper on
RenderOptions (e.g. pub(crate) fn strip_wrapper_extras(self) -> Self) that
iterates a single const slice (e.g. WRAPPER_EXTRA_KEYS =
&["inner","effect","boot_lines","font_sequence"]) and calls without_extra for
each key, then replace each inner_options implementation to call
RenderOptions::strip_wrapper_extras(); update wrappers that call
parse_specific() to use the centralized helper so the list of keys lives in one
place.
- Around line 211-223: The test inner_options_strips_wrapper_fields only sets
the "inner" extra, so it doesn't verify that "effect", "boot_lines", and
"font_sequence" are stripped; update the test to pre-populate all four extras
(e.g., call
RenderOptions::default().with_extra("inner","text_ascii").with_extra("effect","...").with_extra("boot_lines","...").with_extra("font_sequence","..."))
and then assert that inner_options(&opts).parse_specific() has
parsed.inner.is_none() and that the Options returned by inner_options has
duration_ms None and style preserved and, crucially, that effect, boot_lines,
and font_sequence are also removed; alternatively replace the body with a call
to the shared helper strip_wrapper_extras that pre-populates and asserts removal
for all four keys so the test fails if the strip list drifts.

In `@src/render/gauge_circle.rs`:
- Around line 9-20: The current parse_specific flow hides serde errors by using
unwrap_or_default in parse_specific (called from src/render/mod.rs) so
#[serde(deny_unknown_fields)] on types like Options in gauge_circle.rs and
grid_calendar.rs is effectively ignored; update parse_specific to return
Result<T, serde_yaml::Error> (or a suitable Error) instead of unwrapping to
default, and change callers (renderers that call parse_specific) to handle Err
by returning/producing an in-band error string for the renderer; alternatively,
if you prefer to accept silent defaults, remove #[serde(deny_unknown_fields)]
and the misleading comments in gauge_circle.rs and grid_calendar.rs—pick one
approach and make consistent changes to parse_specific and all call sites (and
adjust function signatures) accordingly.

In `@src/render/mod.rs`:
- Around line 192-199: The parse_specific function currently swallows
deserialization errors via .unwrap_or_default(), which causes wrapper renderer
Options (e.g., animated_postfx::Options and other wrapper renderers using
deny_unknown_fields) to silently drop inner fields; replace the
.unwrap_or_default() call in parse_specific with explicit error handling: match
the toml::Value::Table(self.raw.clone()).try_into() result, and on Err(e) log a
clear warning including the error message and the offending self.raw (so
typos/unknown keys are visible) and then return T::default(); on Ok(v) return v.
This makes deserialization failures observable while preserving the existing
fallback behavior.

---

Nitpick comments:
In `@src/install/preview.rs`:
- Around line 264-284: Replace the ad-hoc serde Wrapper parsing in
inner_renderer_name and font_sequence with the new RenderOptions accessors: call
opts.extra_str("inner") and use its Some value or default to "text_plain" for
inner_renderer_name, and call opts.extra_string_array("font_sequence") to return
the Option<Vec<String>> for font_sequence; this removes the Wrapper structs and
avoids parse_specific/deny_unknown_fields behavior while preserving the same
return semantics.

In `@src/render/animated_wave.rs`:
- Around line 183-192: The current inner_options function in animated_wave.rs
enumerates other wrappers' keys (effect, boot_lines, font_sequence) which is
fragile; instead add a centralized list or helper and use that here: create a
single WRAPPER_KEYS constant (or implement
RenderOptions::without_wrapper_extras(&self)) that contains all wrapper-specific
keys, and change inner_options to clone opts and call the new helper (e.g.,
opts.clone().without_extras(&WRAPPER_KEYS) or
opts.clone().without_wrapper_extras()) so wrappers no longer need to know each
other's keys and new wrapper keys only require updating the single central
list/helper.

In `@src/render/chart_bar.rs`:
- Around line 14-28: Tests don't exercise the new per-renderer Options being
parsed from a RenderSpec end-to-end; add a small unit/integration test that
constructs a RenderSpec::Full containing the options keys (e.g., "horizontal":
true and "max_bars": 2 or "bar_width": N) and calls parse_specific() to ensure
the produced Options struct (and downstream behavior) reflects those values
rather than defaults. Locate the parsing path that produces Options (the Options
struct in chart_bar.rs and the parse_specific() call site) and assert that
Options.horizontal, Options.max_bars, and Options.bar_width are set as expected
when parsed through RenderSpec::Full so future regressions are caught.

In `@src/render/grid_table.rs`:
- Around line 84-90: The dispatch in render uses mixed parameter
types—render_rows(&Options) vs render_inline(&RenderOptions)—which is
inconsistent; update the helper signatures so both accept the same type: either
change render_inline to take &Options (the parsed specific) or change
render_rows to take &RenderOptions and let each helper call parse_specific() as
needed; adjust all call sites (including the other occurrences around lines
109-115) and update parameter names in render_inline, render_rows, and any
internal uses of align or specific fields (Options, RenderOptions,
parse_specific, render_inline, render_rows, render) to match the unified
signature.

In `@src/render/media_image.rs`:
- Around line 102-118: compute_target and render_image both call
opts.parse_specific(), causing duplicate parsing; parse the specific Options
once in the caller (e.g., in render before calling compute_target and
render_image), store it in a local variable (Options) and pass a reference
(&Options) into compute_target and render_image instead of calling
parse_specific() inside them; update function signatures to accept the &Options
reference where needed (compute_target(..., opts: &RenderOptions, specific:
&Options) or compute_target(..., specific: &Options)) and remove the internal
parse_specific() calls in render_image and the other helper (also adjust the
second site mentioned around the 130-138 region), ensuring all uses reference
the single parsed Options instance.

In `@src/render/mod.rs`:
- Around line 173-184: The field RenderOptions::raw is public but callers should
use with_extra/without_extra; change its visibility to pub(crate) to prevent
downstream mutation (update any xtask consumers by adding a crate-level
re-export/shim if needed), or if you must keep it public for tests/xtask,
annotate it with #[doc(hidden)] and keep the existing
extra_str/extra_string_array helpers for snapshot reads; ensure code references
to raw in tests or xtask are adjusted to use the shim or remain accessible via
the intended visibility.
🪄 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: 066bbeb1-0896-424f-9e64-ae010220bbef

📥 Commits

Reviewing files that changed from the base of the PR and between 643c3da and 3f84f4c.

📒 Files selected for processing (22)
  • src/install/preview.rs
  • src/render/animated_boot.rs
  • src/render/animated_figlet_morph.rs
  • src/render/animated_postfx.rs
  • src/render/animated_scanlines.rs
  • src/render/animated_splitflap.rs
  • src/render/animated_wave.rs
  • src/render/chart_bar.rs
  • src/render/chart_histogram.rs
  • src/render/chart_pie.rs
  • src/render/chart_scatter.rs
  • src/render/gauge_circle.rs
  • src/render/gauge_segment.rs
  • src/render/grid_calendar.rs
  • src/render/grid_heatmap.rs
  • src/render/grid_table.rs
  • src/render/list_timeline.rs
  • src/render/media_image.rs
  • src/render/mod.rs
  • src/render/status_badge.rs
  • src/render/text_ascii.rs
  • xtask/src/dashboard_snapshot.rs

Comment on lines +386 to 393
// postfx-specific keys are stripped from the forwarded raw blob…
let parsed_inner: Options = inner.parse_specific();
assert!(parsed_inner.inner.is_none());
assert!(parsed_inner.effect.is_none());
// …but the inner renderer still sees its own keys (e.g. text_ascii's pixel_size).
let parsed_text: crate::render::text_ascii::Options = inner.parse_specific();
assert_eq!(parsed_text.pixel_size.as_deref(), Some("quadrant"));
assert!(inner.duration_ms.is_none());

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

This test passes vacuously — it doesn't actually verify the inner/effect stripping.

After inner_options, inner.raw still contains pixel_size (a key unknown to animated_postfx::Options). Because Options uses deny_unknown_fields, parse_specific::<Options>() returns Default regardless of whether inner / effect were stripped — so parsed_inner.inner.is_none() and parsed_inner.effect.is_none() would hold even if without_extra was a no-op.

Verify the stripping directly against raw so the test fails if the helper regresses:

🧪 Proposed assertion
         let inner = inner_options(&opts);
         assert_eq!(inner.style.as_deref(), Some("figlet"));
         assert_eq!(inner.align.as_deref(), Some("center"));
-        // postfx-specific keys are stripped from the forwarded raw blob…
-        let parsed_inner: Options = inner.parse_specific();
-        assert!(parsed_inner.inner.is_none());
-        assert!(parsed_inner.effect.is_none());
+        // postfx-specific keys are stripped from the forwarded raw blob…
+        assert!(inner.extra_str("inner").is_none());
+        assert!(inner.extra_str("effect").is_none());
         // …but the inner renderer still sees its own keys (e.g. text_ascii's pixel_size).
         let parsed_text: crate::render::text_ascii::Options = inner.parse_specific();
         assert_eq!(parsed_text.pixel_size.as_deref(), Some("quadrant"));
         assert!(inner.duration_ms.is_none());
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/render/animated_postfx.rs` around lines 386 - 393, The test is vacuous
because parse_specific::<Options>() returns Default when unknown fields exist;
instead assert against the raw blob to ensure stripping happened: after calling
the helper (e.g. without_extra/inner_options) check inner.raw (the raw
JSON/string map) does not contain the keys "inner" and "effect" (and/or their
serialized forms) and still contains the renderer-specific key "pixel_size" so
parsed_text.pixel_size remains "quadrant"; keep the existing parse_specific
checks for parsed_text but replace or add assertions that directly inspect
inner.raw to confirm "inner" and "effect" were removed.

Comment on lines 183 to 192
fn inner_options(opts: &RenderOptions) -> RenderOptions {
RenderOptions {
inner: None,
effect: None,
duration_ms: None,
boot_lines: None,
font_sequence: None,
..opts.clone()
}
.without_extra("inner")
.without_extra("effect")
.without_extra("boot_lines")
.without_extra("font_sequence")
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Centralize the wrapper-extras strip — root cause for several files.

The inner_options body is duplicated verbatim across animated_scanlines.rs, animated_splitflap.rs (lines 194-203), animated_boot.rs (lines 212-221), and per the PR description also in animated_postfx.rs / animated_wave.rs. The list of stripped keys ("inner", "effect", "boot_lines", "font_sequence") has to stay in lockstep with every wrapper's Options schema — and because each inner renderer uses #[serde(deny_unknown_fields)], a missed key here causes the inner parse_specific() to silently fall back to defaults (no surfaced error). That's the exact failure mode this set of strips is supposed to prevent, and it currently has five copies to keep in sync.

Extract a single helper — e.g. RenderOptions::strip_wrapper_extras(self) -> Self on the type, or a super::wrapper::inner_options(opts) free function — and have every wrapper delegate. The list of wrapper keys then lives in one place and gains a single point of test coverage.

♻️ Sketch (apply once, then call from all five wrappers)
// In src/render/mod.rs (or src/render/wrapper.rs):
pub(crate) const WRAPPER_EXTRA_KEYS: &[&str] =
    &["inner", "effect", "boot_lines", "font_sequence"];

impl RenderOptions {
    pub(crate) fn strip_wrapper_extras(mut self) -> Self {
        for k in WRAPPER_EXTRA_KEYS {
            self = self.without_extra(k);
        }
        self
    }
}
 fn inner_options(opts: &RenderOptions) -> RenderOptions {
     RenderOptions {
         duration_ms: None,
         ..opts.clone()
     }
-    .without_extra("inner")
-    .without_extra("effect")
-    .without_extra("boot_lines")
-    .without_extra("font_sequence")
+    .strip_wrapper_extras()
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/render/animated_scanlines.rs` around lines 183 - 192, The helper logic
that strips wrapper-specific extra keys is duplicated across inner_options in
multiple files; create a single helper on RenderOptions (e.g. pub(crate) fn
strip_wrapper_extras(self) -> Self) that iterates a single const slice (e.g.
WRAPPER_EXTRA_KEYS = &["inner","effect","boot_lines","font_sequence"]) and calls
without_extra for each key, then replace each inner_options implementation to
call RenderOptions::strip_wrapper_extras(); update wrappers that call
parse_specific() to use the centralized helper so the list of keys lives in one
place.

Comment on lines 211 to 223
fn inner_options_strips_wrapper_fields() {
let opts = RenderOptions {
inner: Some("text_ascii".into()),
duration_ms: Some(1500),
style: Some("figlet".into()),
..RenderOptions::default()
};
}
.with_extra("inner", "text_ascii");
let inner = inner_options(&opts);
assert!(inner.inner.is_none());
let parsed: Options = inner.parse_specific();
assert!(parsed.inner.is_none());
assert!(inner.duration_ms.is_none());
assert_eq!(inner.style.as_deref(), Some("figlet"));
}

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

Test only covers stripping of inner — the other three keys are vacuously asserted.

The opts under test only has inner set via with_extra, so the test never demonstrates that effect, boot_lines, or font_sequence are actually removed. If the strip list ever drifts (e.g., someone removes .without_extra("effect")), this test still passes.

If you adopt the shared strip_wrapper_extras helper from the previous comment, this becomes a single test against the helper that pre-populates all four keys via with_extra and asserts each is gone. Otherwise, extend this test in place to inject all four.

♻️ Inline-fix variant
     let opts = RenderOptions {
         duration_ms: Some(1500),
         style: Some("figlet".into()),
         ..RenderOptions::default()
     }
-    .with_extra("inner", "text_ascii");
+    .with_extra("inner", "text_ascii")
+    .with_extra("effect", "fade_in")
+    .with_extra("boot_lines", vec!["a".to_string()])
+    .with_extra("font_sequence", vec!["small".to_string()]);
     let inner = inner_options(&opts);
-    let parsed: Options = inner.parse_specific();
-    assert!(parsed.inner.is_none());
+    let parsed: Options = inner.parse_specific();
+    assert!(parsed.inner.is_none());
+    assert!(inner.extra_str("effect").is_none());
+    assert!(inner.extra_string_array("boot_lines").is_none());
+    assert!(inner.extra_string_array("font_sequence").is_none());
     assert!(inner.duration_ms.is_none());
     assert_eq!(inner.style.as_deref(), Some("figlet"));
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/render/animated_scanlines.rs` around lines 211 - 223, The test
inner_options_strips_wrapper_fields only sets the "inner" extra, so it doesn't
verify that "effect", "boot_lines", and "font_sequence" are stripped; update the
test to pre-populate all four extras (e.g., call
RenderOptions::default().with_extra("inner","text_ascii").with_extra("effect","...").with_extra("boot_lines","...").with_extra("font_sequence","..."))
and then assert that inner_options(&opts).parse_specific() has
parsed.inner.is_none() and that the Options returned by inner_options has
duration_ms None and style preserved and, crucially, that effect, boot_lines,
and font_sequence are also removed; alternatively replace the body with a call
to the shared helper strip_wrapper_extras that pre-populates and asserts removal
for all four keys so the test fails if the strip list drifts.

Comment on lines +9 to +20
/// Reserved forward-compat fields. ratatui's current Gauge widget is a single full-height
/// bar so neither field has a visible effect yet; declared here for `deny_unknown_fields`
/// parity with the documented schema.
#[derive(Debug, Clone, Default, serde::Deserialize)]
#[serde(deny_unknown_fields)]
#[allow(dead_code)]
struct Options {
#[serde(default)]
pub ring_thickness: Option<u16>,
#[serde(default)]
pub label_position: Option<String>,
}

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 | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect parse_specific's signature and body to confirm error handling.
fd -e rs | xargs rg -nP -C5 'fn\s+parse_specific\b'
echo '---'
# And the with_extra builder (used in list_timeline tests)
fd -e rs | xargs rg -nP -C3 'fn\s+with_extra\b|fn\s+without_extra\b'
echo '---'
# Sanity check: any existing test that exercises an unknown key against parse_specific?
rg -nP 'parse_specific|deny_unknown_fields' --type=rs -C2

Repository: unhappychoice/splashboard

Length of output: 2000


🏁 Script executed:

# Get complete parse_specific implementation and surrounding context
sed -n '185,205p' src/render/mod.rs

Repository: unhappychoice/splashboard

Length of output: 1164


🏁 Script executed:

# Search for tests that exercise parse_specific with invalid keys
rg 'parse_specific' src/ -A 3 -B 1 --type rust

Repository: unhappychoice/splashboard

Length of output: 14334


🏁 Script executed:

# Check if deny_unknown_fields is actually tested anywhere
rg 'deny_unknown_fields|unknown.*key|bogus' src/ --type rust -C 2

Repository: unhappychoice/splashboard

Length of output: 19620


🏁 Script executed:

# Check gauge_circle.rs and grid_calendar.rs to see how Options is used
echo "=== gauge_circle.rs ===" && sed -n '1,100p' src/render/gauge_circle.rs | head -60
echo "=== grid_calendar.rs ===" && sed -n '1,50p' src/render/grid_calendar.rs 2>/dev/null || echo "File not found or too large"

Repository: unhappychoice/splashboard

Length of output: 3681


parse_specific() silently swallows deny_unknown_fields errors—claims about surfacing unknown keys are false.

The implementation at src/render/mod.rs:192-199 calls .unwrap_or_default() on the deserialization result, which means errors from deny_unknown_fields are caught and silently converted to T::default(). The comments in gauge_circle.rs and grid_calendar.rs claiming "unknown keys still fail per deny_unknown_fields" are misleading—the serde attribute triggers, but the error is hidden.

Invalid renderer-specific configs are never surfaced to users; they silently become defaults instead. This violates the learning requirement that unknown values must render an in-band error string.

Either:

  • Change parse_specific() to return Result<T, Error> and have renderers emit error strings on parse failure, or
  • Accept that unknown keys are silently ignored and remove the deny_unknown_fields derive (which has no effect) and misleading comments.

Confirm which direction this PR intends.

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

In `@src/render/gauge_circle.rs` around lines 9 - 20, The current parse_specific
flow hides serde errors by using unwrap_or_default in parse_specific (called
from src/render/mod.rs) so #[serde(deny_unknown_fields)] on types like Options
in gauge_circle.rs and grid_calendar.rs is effectively ignored; update
parse_specific to return Result<T, serde_yaml::Error> (or a suitable Error)
instead of unwrapping to default, and change callers (renderers that call
parse_specific) to handle Err by returning/producing an in-band error string for
the renderer; alternatively, if you prefer to accept silent defaults, remove
#[serde(deny_unknown_fields)] and the misleading comments in gauge_circle.rs and
grid_calendar.rs—pick one approach and make consistent changes to parse_specific
and all call sites (and adjust function signatures) accordingly.

Comment thread src/render/mod.rs
Comment on lines +192 to +199
pub fn parse_specific<T: serde::de::DeserializeOwned + Default>(&self) -> T {
if self.raw.is_empty() {
return T::default();
}
toml::Value::Table(self.raw.clone())
.try_into()
.unwrap_or_default()
}

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:

#!/bin/bash
# Confirm wrapper renderers ship Options with deny_unknown_fields, so the cascade above is reachable.
rg -nP -B1 -A3 'deny_unknown_fields' --type=rust -g 'src/render/animated_*.rs'
# And spot any tests that mix inner-renderer keys on a wrapper's top level today.
rg -nP -B2 -A6 'animated_postfx|animated_wave|animated_boot|animated_figlet_morph' --type=rust -g 'tests/**' -g 'templates/**'

Repository: unhappychoice/splashboard

Length of output: 2223


🏁 Script executed:

#!/bin/bash
# Examine parse_specific implementation and surrounding context
sed -n '180,210p' src/render/mod.rs

# Check where parse_specific is called and how raw is populated
rg -n 'parse_specific' --type=rust src/render/

# Look for test cases exercising wrapper renderers with configs
rg -n 'animated_postfx|animated_wave|animated_boot|animated_figlet_morph' --type=rust -A5 -B2

Repository: unhappychoice/splashboard

Length of output: 26194


unwrap_or_default() + deny_unknown_fields on wrapper renderer Options silently drops all renderer specifics on an unknown key.

Concrete example: a config like render = { type = "animated_postfx", inner = "text_ascii", effect = "dissolve", pixel_size = "quadrant" } leaves raw = { inner, effect, pixel_size }. animated_postfx::Options uses deny_unknown_fields and doesn't declare pixel_size, so try_into() returns Err, and unwrap_or_default() collapses the struct to inner: None, effect: None. The render path then silently falls back to default_renderer_for(shape) — the user's inner and effect are lost without any diagnostic.

The same trap fires for typos. All wrapper renderers (animated_postfx, animated_wave, animated_boot, animated_boot, animated_scanlines, animated_splitflap, animated_figlet_morph) use deny_unknown_fields, making this reachable whenever a user mixes an unknown key (whether a typo or a key intended for a different renderer) into the top-level options table.

Mitigations to consider:

  • Don't use deny_unknown_fields on wrapper Options; they inherently coexist with inner-renderer keys. Leaf renderers can keep it.
  • Or have wrappers grab their single keys via extra_str / extra_string_array instead of Options structs.
  • At minimum, log the deserialize error before unwrap_or_default() so silent drops are observable:
Proposed observability fix
 pub fn parse_specific<T: serde::de::DeserializeOwned + Default>(&self) -> T {
     if self.raw.is_empty() {
         return T::default();
     }
-    toml::Value::Table(self.raw.clone())
-        .try_into()
-        .unwrap_or_default()
+    match toml::Value::Table(self.raw.clone()).try_into() {
+        Ok(v) => v,
+        Err(e) => {
+            tracing::warn!(
+                target: "splashboard::render",
+                error = %e,
+                "renderer-specific options failed to parse; falling back to defaults"
+            );
+            T::default()
+        }
+    }
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/render/mod.rs` around lines 192 - 199, The parse_specific function
currently swallows deserialization errors via .unwrap_or_default(), which causes
wrapper renderer Options (e.g., animated_postfx::Options and other wrapper
renderers using deny_unknown_fields) to silently drop inner fields; replace the
.unwrap_or_default() call in parse_specific with explicit error handling: match
the toml::Value::Table(self.raw.clone()).try_into() result, and on Err(e) log a
clear warning including the error message and the offending self.raw (so
typos/unknown keys are visible) and then return T::default(); on Ok(v) return v.
This makes deserialization failures observable while preserving the existing
fallback behavior.

@unhappychoice
unhappychoice merged commit fe6bf16 into main Apr 26, 2026
7 checks passed
@unhappychoice
unhappychoice deleted the refactor/render-options-split branch April 26, 2026 05:05
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.

1 participant