Skip to content

feat(theme): semantic color keys with [theme] overrides (#17) - #72

Merged
unhappychoice merged 10 commits into
mainfrom
feat/theme-color-keys-17
Apr 22, 2026
Merged

unhappychoice merged 10 commits into
mainfrom
feat/theme-color-keys-17

Conversation

@unhappychoice

@unhappychoice unhappychoice commented Apr 22, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • 全レンダラーの色参照を ratatui::Color::X リテラルから意味キー(status_ok/muted/today/series/heatmap_ramp…)経由に。
  • ユーザーは config.toml の新 [theme] セクションで任意のキーを上書き可。ratatui 純正の Color deserialize に任せているので "cyan" でも "#40c463" でも配列でも通る。
  • Renderer::color_keys() を追加して、各レンダラーが自分の使う意味キーをコードで宣言。xtask の docs 生成がそれを拾って renderer ページに Theme tokens 表を自動で出すので、コードとドキュメントがずれない。
  • Renderer::render のシグネチャに &Theme を追加(選択肢 a)。runtime::run で Theme::from_config(&config.theme) を1回構築、layout/test_utils/xtask snapshots まで経路を通した。
  • chart_line もついでに series パレットで色付け(これまで無色)。

新規ファイル: src/theme.rs のみ。主要な挙動の差分は grid_heatmap の GitHub-green ランプや status 三色など、デフォルト値は従来と完全一致。

#17

Test plan

  • cargo test --all-targets — 326 passed
  • cargo clippy --all-targets -- -D warnings — clean
  • cargo run -p xtask — 全 renderer の Markdown ページに Theme tokens セクションが出ることを確認

フォロー候補(別 PR)

  • ビルトインテーマ (nord / tokyo-night / dracula / gruvbox) の theme.preset = "..." 切替
  • per-widget 上書き (render = { type = "status_badge", status_ok = "cyan" })
  • docs サイトに theme の総合解説ページ

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Full theming system with multiple built-in presets, theme token overrides, and palette/heatmap support.
    • Configurable global padding and per-row subtle background styling; viewport now paints themed background.
    • Renderers updated to respect theme colors across text, charts, tables, calendars, badges, and images.
  • Documentation

    • Generated renderer docs now include which theme tokens each renderer consumes.

@coderabbitai

coderabbitai Bot commented Apr 22, 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 52 minutes and 56 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 52 minutes and 56 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: 4591f4ca-a99d-481a-9216-cfb364bd8a2f

📥 Commits

Reviewing files that changed from the base of the PR and between c195186 and 2db24fc.

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

Walkthrough

Adds a semantic theming system with tokenized Theme and presets, threads Theme and padding through runtime, layout, and renderer APIs, updates renderers to declare consumed tokens and apply theme colors, and adds config/preset parsing and docs generation for renderer theme tokens.

Changes

Cohort / File(s) Summary
Theme Core
Cargo.toml, src/lib.rs, src/theme/mod.rs, src/theme/presets.rs
New theming module: ColorKey tokens, Theme + ThemeConfig, presets, defaults, palette helpers, and serde-enabled ratatui feature.
Configuration & Examples
src/config.rs, .splashboard/config.toml
Config gains theme: ThemeConfig, General.padding (uniform or {x,y}), BgSpec for row/child bg; example TOML updated with padding and bg = "subtle".
Layout & Backgrounds
src/layout.rs
Added BgLevel and with_bg(), background painting (paint_bg), and threaded theme: &Theme through public draw and rendering chain.
Runtime Plumbing
src/runtime.rs
run builds Theme::from_config, extracts padding, threads &Theme and padding into draw/flush/finalize paths, paints viewport bg, and renders into a padded content rect.
Renderer API Surface
src/render/mod.rs, src/render/test_utils.rs
Renderer trait extended with color_keys() and theme: &Theme parameter for render(); render_payload() and test utils updated to pass &Theme. Empty/error rendering now theme-styled.
Renderers — Charts & Visuals
src/render/chart_*.rs, src/render/chart_pie.rs, src/render/chart_scatter.rs, src/render/chart_bar.rs, src/render/chart_line.rs, src/render/chart_sparkline.rs
All chart renderers accept theme and most declare color_keys(); series/palette coloring now uses theme.series_color(i) and pie/heat palettes use theme palettes instead of hardcoded colors.
Renderers — Grids & Tables
src/render/grid_calendar.rs, src/render/grid_heatmap.rs, src/render/grid_table.rs
Calendar and heatmap use theme tokens (accent_today, accent_event, heatmap_level); table uses theme.text base and status_badge::status_color(..., theme) for status colors.
Renderers — Lists, Text, Media, Gauges, Status
src/render/list_*.rs, src/render/text_*.rs, src/render/media_image.rs, src/render/gauge_*.rs, src/render/status_badge.rs, src/render/animated_typewriter.rs
All updated to accept theme and expose color_keys() where relevant; widgets apply theme.text/text_dim/text_secondary and status/gauge/media/status badge colors come from theme.
Docs & Tooling
xtask/src/gen_matrix.rs, xtask/src/snapshots.rs
Generator now emits a "Theme tokens" section per renderer (or a note when none), and snapshots pipeline passes Theme::default() into rendering for HTML snapshots.

Sequence Diagram

sequenceDiagram
    participant Config as Config (TOML)
    participant Runtime as Runtime
    participant Theme as Theme Builder
    participant Layout as Layout System
    participant Renderers as Renderers

    Config->>Runtime: load config (theme, padding)
    Runtime->>Theme: Theme::from_config(cfg.theme)
    Theme-->>Runtime: Theme instance
    Runtime->>Layout: layout::draw(area, layout, specs, registry, &Theme)
    Layout->>Layout: apply BgLevel and paint_bg(theme)
    Layout->>Renderers: invoke renderer.render(..., &Theme)
    Renderers->>Renderers: use theme.text / series_color(i) / heatmap_level(...)
    Renderers-->>Layout: draw widgets with themed styles
    Layout-->>Runtime: composed frame
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰 I munched a config leaf tonight,
Tokens bright and presets right,
Themes hop in (subtle, bold),
Renderers now wear hues untold,
Widgets glow — a rabbit’s delight! 🎨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 71.04% 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 clearly and accurately summarizes the main change: introducing semantic color keys and [theme] configuration overrides, which is the primary objective of this substantial changeset across renderers, config, layout, and a new theme module.
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 unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/theme-color-keys-17

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.

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

🧹 Nitpick comments (7)
src/theme.rs (1)

157-197: Move ThemeConfig above private helpers.

ThemeConfig is public but currently sits below private helper functions. Please keep all public structs/constants grouped before private implementation details. As per coding guidelines, src/**/*.rs: Place public items at the top of source files.

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

In `@src/theme.rs` around lines 157 - 197, ThemeConfig (pub struct ThemeConfig) is
declared below private helper functions default_series and default_heatmap_ramp;
move the public item above those private helpers so public API is grouped before
implementation details. Reorder the code by cutting the entire ThemeConfig
definition (including its derives and serde attributes) and pasting it above the
two helper functions (default_series, default_heatmap_ramp), leaving the helpers
as private implementation below; keep all derives, visibility, and serde
attributes unchanged.
src/render/test_utils.rs (1)

26-28: Consider adding themed variants of these helpers.

Using Theme::default() preserves existing tests, but custom [theme] behavior will be easier to verify if tests can pass a non-default Theme through the shared helpers instead of duplicating setup. As per coding guidelines, use src/render/test_utils.rs helpers (render_to_buffer*()) for rendering tests; scan returned Buffer for expected cells/symbols.

Also applies to: 52-56

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

In `@src/render/test_utils.rs` around lines 26 - 28, Add themed variants of the
shared rendering helpers so tests can pass a non-default Theme: update the
helpers used in src/render/test_utils.rs (the render_to_buffer* family) to
accept a Theme or &Theme parameter instead of calling Theme::default()
internally, and propagate that Theme into the call site that currently invokes
render_payload (which takes a theme reference). Modify usages that currently
rely on Theme::default() to call the new themed helpers—this applies to the
helper around render_payload and the other helper group referenced in the
comment—so tests can pass custom Theme instances without duplicating setup.
src/render/mod.rs (1)

311-337: Consider adding a test that exercises theme.muted override.

The default-theme path is covered by the existing empty_body_renders_placeholder_not_specific_renderer test, but there's no coverage asserting that a non-default theme.muted actually drives the foreground of the "nothing here yet" placeholder. A small unit test that constructs a Theme with a custom muted color and scans buf.cell(...).fg would prevent silent regressions if this wiring ever gets swapped for a hard-coded color again.

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

In `@src/render/mod.rs` around lines 311 - 337, Add a unit test that verifies
render_empty_state uses Theme::muted for the placeholder foreground: create a
Theme with a non-default muted Color, call render_empty_state (or the
higher-level render that invokes it) producing a buffer, then assert the buffer
cell(s) for the "nothing here yet" text have fg equal to that custom Theme.muted
(e.g., via buf.cell(x,y).fg). Reference render_empty_state, Theme.muted, and the
existing test empty_body_renders_placeholder_not_specific_renderer as a template
for setup and assertions. Ensure the test covers both single-line and two-line
layouts if possible by varying the area.height.
src/runtime.rs (2)

576-583: Nit: argument order is inconsistent with the rest of the file.

draw, draw_final, and draw_frame all place theme before hidden_rows, but render_clip_hint puts theme last. Swap them for symmetry — no behavior change, just reads more predictably at call sites.

♻️ Proposed tweak
-fn render_clip_hint(frame: &mut Frame, area: Rect, hidden_rows: u16, theme: &Theme) {
+fn render_clip_hint(frame: &mut Frame, area: Rect, theme: &Theme, hidden_rows: u16) {

Update the call site on line 570 and the two test sites accordingly.

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

In `@src/runtime.rs` around lines 576 - 583, render_clip_hint currently takes
(frame, area, hidden_rows, theme) which is inconsistent with draw, draw_final,
and draw_frame that pass theme before hidden_rows; change the signature of
render_clip_hint to fn render_clip_hint(frame: &mut Frame, area: Rect, theme:
&Theme, hidden_rows: u16) and update its single call site (around the previous
line ~570) plus the two test sites to pass theme before hidden_rows so call
sites and signature match the rest of the file (references: render_clip_hint,
draw, draw_final, draw_frame).

489-574: Consider bundling draw args into a context struct instead of growing #[allow(clippy::too_many_arguments)] usage.

draw, draw_final, and draw_frame now each carry 7–8 parameters and all need the clippy suppression. A small DrawCtx<'a> { root, payloads, specs, registry, theme, hidden_rows } passed by reference would drop every allow, keep call sites readable, and make future additions (e.g. focus state, a palette handle for panels) a one-line change instead of editing three signatures plus their callers. Not a blocker — purely maintainability.

♻️ Sketch
struct DrawCtx<'a> {
    root: &'a Layout,
    payloads: &'a HashMap<WidgetId, Payload>,
    specs: &'a HashMap<WidgetId, RenderSpec>,
    registry: &'a render::Registry,
    theme: &'a Theme,
    hidden_rows: u16,
}

fn draw<B: Backend>(terminal: &mut Terminal<B>, ctx: &DrawCtx<'_>) -> io::Result<()> { ... }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/runtime.rs` around lines 489 - 574, Bundle the repeated draw parameters
into a single context struct (e.g. struct DrawCtx<'a> { root: &'a Layout,
payloads: &'a HashMap<WidgetId, Payload>, specs: &'a HashMap<WidgetId,
RenderSpec>, registry: &'a render::Registry, theme: &'a Theme, hidden_rows: u16
}), then change the signatures of draw, draw_final, and draw_frame to accept
&DrawCtx instead of the 6–7 individual params (keeping Terminal/B/Frame/area
where needed). Update all call sites to construct/passthrough a &DrawCtx and use
ctx.* inside the closures and inside draw_frame (and forward ctx to any
downstream helpers such as layout::draw or render_clip_hint that need those
values). Remove the #[allow(clippy::too_many_arguments)] annotations afterward.
src/render/list_timeline.rs (2)

15-21: COLOR_KEYS correctly reflects transitive token usage.

Including STATUS_OK/STATUS_WARN/STATUS_ERROR here even though those colors are resolved inside status_badge::status_color is the right call — the xtask docs table should show every [theme] key a user might tweak to change this renderer's output. Worth leaving a short comment about that intent so a future cleanup pass doesn't "simplify" the list down to just MUTED/SECONDARY and silently break the generated docs.

📝 Suggested comment
+// Includes status_* tokens because status-coloured titles resolve through
+// status_badge::status_color — xtask docs must list every token that affects output.
 const COLOR_KEYS: &[ColorKey] = &[
     theme::STATUS_OK,
     theme::STATUS_WARN,
     theme::STATUS_ERROR,
     theme::MUTED,
     theme::SECONDARY,
 ];

Also applies to: 37-39

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

In `@src/render/list_timeline.rs` around lines 15 - 21, Add a short explanatory
comment above the COLOR_KEYS constant stating that it intentionally lists
transitive [theme] keys (including theme::STATUS_OK, theme::STATUS_WARN,
theme::STATUS_ERROR) because those tokens are used indirectly by
status_badge::status_color and must be documented for xtask docs; do the same
for the other COLOR_KEYS occurrence (the one that includes
theme::MUTED/theme::SECONDARY at lines corresponding to the second list) so
future cleanups won't remove transitive keys.

310-325: Test couples to the default theme's concrete status color.

status_colours_the_title asserts Color::Red for Status::Error, which is correct today but encodes the default theme.status_error value rather than the mapping under test. If someone later changes the default status_error in Theme::default() (e.g. to a hex), this test fails for an unrelated reason. Consider constructing an explicit Theme with a distinct sentinel color for status_error and passing it through — that way the test verifies "Error → theme.status_error" instead of "Error → Red".

♻️ Sketch
let theme = Theme { status_error: Color::Magenta, ..Theme::default() };
// render via a variant of render_at that accepts &theme, then:
assert_eq!(buf.cell((col, 0)).unwrap().fg, Color::Magenta);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/render/list_timeline.rs` around lines 310 - 325, Update the test
status_colours_the_title to avoid relying on Theme::default's concrete color:
construct an explicit Theme with a sentinel color for status_error (e.g.
Color::Magenta) via Theme { status_error: <sentinel>, ..Theme::default() },
render the timeline using a render helper that accepts &Theme (add an
overload/variant of render_at or a new render_with_theme that forwards the theme
into the renderer), then assert that buf.cell((col, 0)).unwrap().fg equals the
sentinel color; reference Theme::status_error, the status_colours_the_title
test, and render_at/render_with_theme to locate the changes.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/render/list_timeline.rs`:
- Around line 15-21: Add a short explanatory comment above the COLOR_KEYS
constant stating that it intentionally lists transitive [theme] keys (including
theme::STATUS_OK, theme::STATUS_WARN, theme::STATUS_ERROR) because those tokens
are used indirectly by status_badge::status_color and must be documented for
xtask docs; do the same for the other COLOR_KEYS occurrence (the one that
includes theme::MUTED/theme::SECONDARY at lines corresponding to the second
list) so future cleanups won't remove transitive keys.
- Around line 310-325: Update the test status_colours_the_title to avoid relying
on Theme::default's concrete color: construct an explicit Theme with a sentinel
color for status_error (e.g. Color::Magenta) via Theme { status_error:
<sentinel>, ..Theme::default() }, render the timeline using a render helper that
accepts &Theme (add an overload/variant of render_at or a new render_with_theme
that forwards the theme into the renderer), then assert that buf.cell((col,
0)).unwrap().fg equals the sentinel color; reference Theme::status_error, the
status_colours_the_title test, and render_at/render_with_theme to locate the
changes.

In `@src/render/mod.rs`:
- Around line 311-337: Add a unit test that verifies render_empty_state uses
Theme::muted for the placeholder foreground: create a Theme with a non-default
muted Color, call render_empty_state (or the higher-level render that invokes
it) producing a buffer, then assert the buffer cell(s) for the "nothing here
yet" text have fg equal to that custom Theme.muted (e.g., via buf.cell(x,y).fg).
Reference render_empty_state, Theme.muted, and the existing test
empty_body_renders_placeholder_not_specific_renderer as a template for setup and
assertions. Ensure the test covers both single-line and two-line layouts if
possible by varying the area.height.

In `@src/render/test_utils.rs`:
- Around line 26-28: Add themed variants of the shared rendering helpers so
tests can pass a non-default Theme: update the helpers used in
src/render/test_utils.rs (the render_to_buffer* family) to accept a Theme or
&Theme parameter instead of calling Theme::default() internally, and propagate
that Theme into the call site that currently invokes render_payload (which takes
a theme reference). Modify usages that currently rely on Theme::default() to
call the new themed helpers—this applies to the helper around render_payload and
the other helper group referenced in the comment—so tests can pass custom Theme
instances without duplicating setup.

In `@src/runtime.rs`:
- Around line 576-583: render_clip_hint currently takes (frame, area,
hidden_rows, theme) which is inconsistent with draw, draw_final, and draw_frame
that pass theme before hidden_rows; change the signature of render_clip_hint to
fn render_clip_hint(frame: &mut Frame, area: Rect, theme: &Theme, hidden_rows:
u16) and update its single call site (around the previous line ~570) plus the
two test sites to pass theme before hidden_rows so call sites and signature
match the rest of the file (references: render_clip_hint, draw, draw_final,
draw_frame).
- Around line 489-574: Bundle the repeated draw parameters into a single context
struct (e.g. struct DrawCtx<'a> { root: &'a Layout, payloads: &'a
HashMap<WidgetId, Payload>, specs: &'a HashMap<WidgetId, RenderSpec>, registry:
&'a render::Registry, theme: &'a Theme, hidden_rows: u16 }), then change the
signatures of draw, draw_final, and draw_frame to accept &DrawCtx instead of the
6–7 individual params (keeping Terminal/B/Frame/area where needed). Update all
call sites to construct/passthrough a &DrawCtx and use ctx.* inside the closures
and inside draw_frame (and forward ctx to any downstream helpers such as
layout::draw or render_clip_hint that need those values). Remove the
#[allow(clippy::too_many_arguments)] annotations afterward.

In `@src/theme.rs`:
- Around line 157-197: ThemeConfig (pub struct ThemeConfig) is declared below
private helper functions default_series and default_heatmap_ramp; move the
public item above those private helpers so public API is grouped before
implementation details. Reorder the code by cutting the entire ThemeConfig
definition (including its derives and serde attributes) and pasting it above the
two helper functions (default_series, default_heatmap_ramp), leaving the helpers
as private implementation below; keep all derives, visibility, and serde
attributes unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 368c6904-1d75-468b-80c2-c6a9b41a4f13

📥 Commits

Reviewing files that changed from the base of the PR and between 3cf7942 and eef6084.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (27)
  • Cargo.toml
  • src/config.rs
  • src/layout.rs
  • src/lib.rs
  • src/render/animated_typewriter.rs
  • src/render/chart_bar.rs
  • src/render/chart_line.rs
  • src/render/chart_pie.rs
  • src/render/chart_scatter.rs
  • src/render/chart_sparkline.rs
  • src/render/gauge_circle.rs
  • src/render/gauge_line.rs
  • src/render/grid_calendar.rs
  • src/render/grid_heatmap.rs
  • src/render/grid_table.rs
  • src/render/list_plain.rs
  • src/render/list_timeline.rs
  • src/render/media_image.rs
  • src/render/mod.rs
  • src/render/status_badge.rs
  • src/render/test_utils.rs
  • src/render/text_ascii.rs
  • src/render/text_plain.rs
  • src/runtime.rs
  • src/theme.rs
  • xtask/src/gen_matrix.rs
  • xtask/src/snapshots.rs

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

Caution

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

⚠️ Outside diff range comments (1)
src/render/text_ascii.rs (1)

49-61: ⚠️ Potential issue | 🟡 Minor

Declare animates() explicitly for this renderer.

TextAsciiRenderer currently relies on the trait default. That works, but renderer implementations in this repo are expected to declare the boolean explicitly.

Proposed fix
     fn accepts(&self) -> &[Shape] {
         &[Shape::Text]
     }
+    fn animates(&self) -> bool {
+        false
+    }
     fn option_schemas(&self) -> &[OptionSchema] {
         OPTION_SCHEMAS
     }

As per coding guidelines, src/render/**/*.rs: “Renderers must declare name() (config key using family_variant convention), accepts() (list of compatible Shapes), animates() (boolean), and render(frame, area, body, opts) implementation”.

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

In `@src/render/text_ascii.rs` around lines 49 - 61, The impl for Renderer on
TextAsciiRenderer is missing an explicit animates() method; add fn
animates(&self) -> bool in the impl block for TextAsciiRenderer (the same impl
that contains name(), accepts(), option_schemas(), color_keys()) and return the
appropriate boolean (likely false for a static ASCII text renderer) so the
renderer explicitly declares animation capability per the Renderer trait
requirements.
🧹 Nitpick comments (3)
src/theme/mod.rs (2)

118-130: Nit: two back-to-back comment blocks say roughly the same thing.

Lines 118-123 and 124-130 both explain the "Reset for chrome, opinionated accents, disable bg on light terminals" story. Collapsing to one block keeps the intent but halves the reading cost.

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

In `@src/theme/mod.rs` around lines 118 - 130, There are two consecutive doc
comments repeating the same rationale for the "Signature palette" (mentioning
Color::Reset for chrome, opinionated sRGB accents, and the option to disable bg
with [theme] bg = "reset"); remove the redundant block so only one consolidated
comment remains above the palette definition, keeping the key phrases (e.g.,
"Signature palette", Color::Reset, bg / bg_subtle, text, border, and the [theme]
bg = "reset" note) so readers still see the intent without duplication in
src/theme/mod.rs near the palette definitions.

160-167: Optional: simplify heatmap_level and avoid per-call allocation on the fallback.

The let ramp = if … { return … } else { &self.heatmap_ramp }; shape is unusual, and default_heatmap_ramp() allocates a 5-element Vec<Color> just to index once. A const fallback keeps both branches cheap and reads more directly:

♻️ Proposed refactor
-    /// Heatmap level in `0..5`, saturating at both ends. Empty ramp falls back to default.
-    pub fn heatmap_level(&self, level: usize) -> Color {
-        let ramp = if self.heatmap_ramp.is_empty() {
-            return default_heatmap_ramp()[level.min(4)];
-        } else {
-            &self.heatmap_ramp
-        };
-        ramp[level.min(ramp.len() - 1)]
-    }
+    /// Heatmap level in `0..5`, saturating at both ends. Empty ramp falls back to default.
+    pub fn heatmap_level(&self, level: usize) -> Color {
+        const FALLBACK: [Color; 5] = [
+            Color::Rgb(0x12, 0x1f, 0x36),
+            Color::Rgb(0x4a, 0x4a, 0x7a),
+            Color::Rgb(0xa0, 0x5e, 0x7a),
+            Color::Rgb(0xff, 0x8c, 0x7a),
+            Color::Rgb(0xff, 0xc6, 0x6b),
+        ];
+        let ramp: &[Color] = if self.heatmap_ramp.is_empty() {
+            &FALLBACK
+        } else {
+            &self.heatmap_ramp
+        };
+        ramp[level.min(ramp.len() - 1)]
+    }

If you keep the fallback constants in sync with default_heatmap_ramp(), worth adding a tiny debug_assert_eq! in tests so the two can't drift.

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

In `@src/theme/mod.rs` around lines 160 - 167, The current heatmap_level function
allocates default_heatmap_ramp() on each fallback and uses a strange if-return
pattern; change it to use a static/const slice (e.g. DEFAULT_HEATMAP_RAMP as
&'static [Color]) and make ramp a slice reference that points to either
&self.heatmap_ramp or DEFAULT_HEATMAP_RAMP, then index with
level.min(ramp.len()-1) and return that Color; also add a debug-only test with
debug_assert_eq! to ensure DEFAULT_HEATMAP_RAMP matches the existing
default_heatmap_ramp() contents so they can't drift.
src/theme/presets.rs (1)

29-49: Optional: drive by_name from a single data source to prevent drift.

KNOWN and the by_name match arms are two parallel lists. Today the test covers KNOWN → by_name, but the reverse direction (a preset reachable via by_name but missing from KNOWN) would silently break the "unknown preset" error message and the xtask catalog. Not urgent, but a table keeps them in lockstep:

♻️ Single-source preset table
-pub const KNOWN: &[&str] = &[
-    "tokyo_night",
-    "nord",
-    "dracula",
-    "gruvbox_dark",
-    "catppuccin_mocha",
-];
-
-pub fn by_name(name: &str) -> Option<Theme> {
-    match name {
-        "tokyo_night" => Some(tokyo_night()),
-        "nord" => Some(nord()),
-        "dracula" => Some(dracula()),
-        "gruvbox_dark" => Some(gruvbox_dark()),
-        "catppuccin_mocha" => Some(catppuccin_mocha()),
-        _ => None,
-    }
-}
+type PresetFn = fn() -> Theme;
+const PRESETS: &[(&str, PresetFn)] = &[
+    ("tokyo_night", tokyo_night),
+    ("nord", nord),
+    ("dracula", dracula),
+    ("gruvbox_dark", gruvbox_dark),
+    ("catppuccin_mocha", catppuccin_mocha),
+];
+
+pub const KNOWN: &[&str] = &[
+    "tokyo_night", "nord", "dracula", "gruvbox_dark", "catppuccin_mocha",
+];
+
+pub fn by_name(name: &str) -> Option<Theme> {
+    PRESETS.iter().find(|(n, _)| *n == name).map(|(_, f)| f())
+}

(Or make KNOWN derive from PRESETS directly and drop it as a separate const.)

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

In `@src/theme/presets.rs` around lines 29 - 49, Replace the duplicated preset
lists by introducing a single source (e.g., a static PRESETS table) that pairs
preset names with their constructor functions, then derive KNOWN from PRESETS'
names and implement by_name to look up/iterate that PRESETS table (matching on
the name and calling the associated constructor, e.g., tokyo_night, nord,
dracula, gruvbox_dark, catppuccin_mocha) so KNOWN and by_name cannot drift
apart; update references to use PRESETS and remove the separate hard-coded KNOWN
match arms.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@src/render/text_ascii.rs`:
- Around line 49-61: The impl for Renderer on TextAsciiRenderer is missing an
explicit animates() method; add fn animates(&self) -> bool in the impl block for
TextAsciiRenderer (the same impl that contains name(), accepts(),
option_schemas(), color_keys()) and return the appropriate boolean (likely false
for a static ASCII text renderer) so the renderer explicitly declares animation
capability per the Renderer trait requirements.

---

Nitpick comments:
In `@src/theme/mod.rs`:
- Around line 118-130: There are two consecutive doc comments repeating the same
rationale for the "Signature palette" (mentioning Color::Reset for chrome,
opinionated sRGB accents, and the option to disable bg with [theme] bg =
"reset"); remove the redundant block so only one consolidated comment remains
above the palette definition, keeping the key phrases (e.g., "Signature
palette", Color::Reset, bg / bg_subtle, text, border, and the [theme] bg =
"reset" note) so readers still see the intent without duplication in
src/theme/mod.rs near the palette definitions.
- Around line 160-167: The current heatmap_level function allocates
default_heatmap_ramp() on each fallback and uses a strange if-return pattern;
change it to use a static/const slice (e.g. DEFAULT_HEATMAP_RAMP as &'static
[Color]) and make ramp a slice reference that points to either
&self.heatmap_ramp or DEFAULT_HEATMAP_RAMP, then index with
level.min(ramp.len()-1) and return that Color; also add a debug-only test with
debug_assert_eq! to ensure DEFAULT_HEATMAP_RAMP matches the existing
default_heatmap_ramp() contents so they can't drift.

In `@src/theme/presets.rs`:
- Around line 29-49: Replace the duplicated preset lists by introducing a single
source (e.g., a static PRESETS table) that pairs preset names with their
constructor functions, then derive KNOWN from PRESETS' names and implement
by_name to look up/iterate that PRESETS table (matching on the name and calling
the associated constructor, e.g., tokyo_night, nord, dracula, gruvbox_dark,
catppuccin_mocha) so KNOWN and by_name cannot drift apart; update references to
use PRESETS and remove the separate hard-coded KNOWN match arms.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: b2c9b828-4fd9-4bf7-a91a-b6921b1d9604

📥 Commits

Reviewing files that changed from the base of the PR and between eef6084 and 67ea981.

📒 Files selected for processing (13)
  • .splashboard/config.toml
  • src/config.rs
  • src/layout.rs
  • src/render/animated_typewriter.rs
  • src/render/list_plain.rs
  • src/render/list_timeline.rs
  • src/render/mod.rs
  • src/render/status_badge.rs
  • src/render/text_ascii.rs
  • src/render/text_plain.rs
  • src/runtime.rs
  • src/theme/mod.rs
  • src/theme/presets.rs
🚧 Files skipped from review as they are similar to previous changes (7)
  • src/render/status_badge.rs
  • src/render/animated_typewriter.rs
  • src/render/text_plain.rs
  • src/layout.rs
  • src/render/list_plain.rs
  • src/config.rs
  • src/render/mod.rs

@unhappychoice
unhappychoice force-pushed the feat/theme-color-keys-17 branch from a761a82 to 802e8cc Compare April 22, 2026 14:51
unhappychoice and others added 6 commits April 22, 2026 23:55
`[theme]` accepts `Color`-typed TOML values (e.g. `status_ok = "cyan"`,
`bg = "#0e172a"`); leans on ratatui's own `Deserialize` impl to parse
named colours + hex, which requires the crate's `serde` feature.

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

New `src/theme/` module — no consumers yet, just types and data:

- `ColorKey` static metadata (name + description) declared per-token.
- `Theme` — resolved palette handed to every `Renderer::render`.
- `ThemeConfig` — TOML layer, overlays on top of the default or a
  selected preset; sibling keys override individual tokens.
- `from_config` resolves preset then applies per-key overlay; unknown
  preset names log to stderr and fall back to the default.

Tokens:
- Surfaces: `bg`, `bg_subtle`
- Chrome ladder: `dim`, `border`, `secondary`, `text`
- Heroes: `title`, `event`
- Status triad: `status_ok`, `status_warn`, `status_error`
- Calendar: `today`, `event`
- Palettes: `series` (10 slots), `heatmap_ramp` (5 stops)

Default theme — "Splash": sunrise over deep ocean. Deep-navy bg
(#0e172a), lifted bg_subtle (#17243b), teal chrome climbing to
diffuse-daylight text (#c5d2dc), coral title (#ff8c7a) + cyan-teal
event (#5ed8e0) as hero warm/cool, amber/mint/coral-red status,
coral↔ocean series cycle, night → shallow → sunrise heatmap ramp.

Presets: `tokyo_night`, `nord`, `dracula`, `gruvbox_dark`,
`catppuccin_mocha` — each carries matching `bg` + `bg_subtle` so
switching preset swaps the full surface.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…olor_keys (#17)

Renderer trait changes:
- `render(frame, area, body, opts, theme: &Theme)` — every renderer
  receives the resolved palette.
- `fn color_keys(&self) -> &[ColorKey] { &[] }` — new method each
  renderer overrides to declare which theme tokens it reads. Picked up
  by xtask so the reference docs list, per renderer, the `[theme]`
  keys that affect it.

Every built-in renderer updated:
- `status_badge`, `grid_table`, `list_timeline` — status triad + dim
  + secondary through the theme.
- `grid_calendar` — `today` / `event` accents.
- `grid_heatmap` — `heatmap_ramp` palette via `Theme::heatmap_level`.
- `chart_pie`, `chart_line`, `chart_scatter` — `series` cycle via
  `Theme::series_color`.
- `text_plain`, `text_ascii` (blocks + figlet), `list_plain`,
  `animated_typewriter` — body copy coloured by `theme.text`.
- Everything else takes `_theme: &Theme` for trait conformance.

`Modifier::DIM` fully removed: every former `fg(theme.muted) +
Modifier::DIM` site now uses `fg(theme.dim)` with a specific colour
so rendering stays consistent across terminals (DIM was rendered as
invisible on some, a no-op on others).

`render_payload` gains `theme: &Theme`, with the empty-state
placeholder now painting via `theme.dim`. xtask's preview snapshots
helper passes a default theme.

Doesn't build in isolation — `layout::draw` and the runtime still
call `render_payload` with the old signature. Fixed in the next
commit together with the full runtime wiring.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…gh draw (#17)

Config:
- `Config.theme: ThemeConfig` — the TOML surface for theme overrides.
- `RowConfig.bg` / `ChildConfig.bg` accept `BgSpec = default | subtle`
  to opt into painting `theme.bg_subtle` behind specific rows or
  widgets (headers, callouts, any band that should lift off the main
  content surface).
- `General.padding: Option<PaddingSpec>` — uniform `padding = 1` or
  split `padding = { x, y }`. `computed_height` accounts for vertical
  padding so the inline viewport sizes to fit rows + padding.

Layout:
- `Layout::Stack` / `Layout::Widget` carry a `BgLevel` each, defaulting
  to `Default` (inherit). `with_bg(...)` chain-sets it.
- `layout::draw` takes `&Theme` and paints `theme.bg_subtle` behind
  any slot whose level is `Subtle`. `Default` / `Reset` levels no-op so
  behaviour is strictly additive.
- `build_block` paints borders via `theme.border` and titles via
  `theme.title`.

Runtime:
- `run()` builds the `Theme` once and the `(pad_x, pad_y)` tuple,
  threads both through `draw` / `draw_final` / `finalize_draw` /
  `flush_full_to_scrollback` / `render_full_into_buffer`.
- New `paint_viewport_bg(frame, area, theme)` fills the whole splash
  area with `theme.bg` before widgets draw so the padded ring takes
  the theme surface instead of leaking the terminal background.
- `render_full_into_buffer` also applies the viewport bg + padding so
  rows flushed to scrollback match the live viewport.
- `draw_frame` shrinks to the content area via `shrink(padding)`; the
  clip hint still lands on the bottom row of the content area.
- `render_clip_hint` uses `theme.dim` (no more `Color::DarkGray` +
  `Modifier::DIM`).

Restores the build after the render API change in the previous commit.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…age (#17)

Each renderer now declares its `color_keys()` — list the declared keys
per renderer's doc so the catalog shows exactly which `[theme]`
tokens affect which renderer. Renders as a `## Theme tokens` section
on `docs-site/.../renderers/<name>.md`; renderers that don't read any
theme colour get an explicit "does not read any `[theme]` tokens"
note so the section is always present and predictable.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…and (#17)

Updates the repo's own `.splashboard/config.toml` to exercise what the
theme system ships with:

- `[general] padding = { x = 2, y = 1 }` so the splash doesn't hug
  the terminal edge; bg paints across the padded ring.
- Hero band (greeting + clock rows) marked `bg = "subtle"` so they
  lift off the main content band via `theme.bg_subtle`.
- No `[theme]` section → uses the built-in Splash default (coral title
  + cyan-teal event on deep-ocean navy); a comment points at the
  shipped presets for folks who want to try one.

`cd`-ing into this repo renders the full palette in context so the
default reads like a real splash, not an abstract test config.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@unhappychoice
unhappychoice force-pushed the feat/theme-color-keys-17 branch from 802e8cc to 4505655 Compare April 22, 2026 14:57
unhappychoice and others added 4 commits April 23, 2026 00:03
…nal fg (#17)

Audit of every text-producing renderer — `theme.text` was only reaching
the plain text family (text_plain / text_ascii / list_plain /
animated_typewriter). Body copy inside other widgets was rendering
with the terminal fg (usually bright white/gray), which looked pasted
on against the navy bg.

Now threaded through:

- `status_badge` — label text (not just the dot).
- `grid_table` — base `Table::style` so rows without status inherit
  `theme.text` instead of terminal fg; per-row status colours still
  patch on top.
- `gauge_circle` / `gauge_line` — labels passed as `Span::styled` so
  the percentage / widget-name text takes the chrome colour.
- `grid_calendar` — `Monthly::default_style` so non-`today` /
  non-`event` day numbers + the header row use `theme.text`.
- `grid_heatmap` — column labels (e.g. "Jan" / "Feb" month markers)
  paint cell fg explicitly.
- `list_timeline` — base paragraph style so event titles without a
  status fall back to `theme.text` rather than terminal fg.
- `chart_bar` — `label_style` + `value_style` for the category names
  and per-bar value readouts.
- `media_image` fallback message.
- `render_error` (in-band unknown-renderer / shape-mismatch text) —
  routes through `theme.status_error` instead of terminal fg, so
  misconfiguration reads as "fix this".

Each renderer declares `theme::TEXT` in its `color_keys()` so the
xtask reference pages list it alongside the other tokens they consume.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Rename tokens so every key carries a consistent family prefix — the
TOML surface stays grep-able and new tokens slot into an obvious
home. Same rule as the renderer-naming convention in AGENTS.md.

  dim          → text_dim
  secondary    → text_secondary
  today        → accent_today
  event        → accent_event
  border       → panel_border
  title        → panel_title
  series       → palette_series
  heatmap_ramp → palette_heatmap

Families after the rename:

- `bg` / `bg_subtle` — surfaces
- `text` / `text_dim` / `text_secondary` — body copy + dim variants
- `panel_border` / `panel_title` — panel chrome
- `status_ok` / `status_warn` / `status_error` — badge triad
- `accent_today` / `accent_event` — calendar / scatter markers
- `palette_series` / `palette_heatmap` — multi-colour palettes

ColorKey constants, Theme / ThemeConfig fields, preset struct
literals, all renderer `color_keys()` declarations, test assertions,
the top-of-module docstring, the TOML test fixture, and the xtask
catalog output all move in lock-step.

Since the previous token names haven't shipped in a release yet, no
migration path / alias is needed.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…"` (#17)

The signature palette was only reachable by omitting `[theme] preset
= "..."` entirely — fine for hand-written configs, awkward for
preset-switching UIs and docs where the default wants a name.

Adds two aliases to `presets::by_name`:

- `"splash"` — the canonical name, matches the palette's identity
  ("sunrise over deep ocean").
- `"default"` — generic keyword for tools that want to say "use the
  built-in".

Both resolve to `Theme::default()` via a new `presets::splash()`
function (exposed for symmetry with `tokyo_night()` / `nord()` /
etc. and so it shows up in the catalog), and both land in `KNOWN` so
error messages listing valid names include them.

The updated top-of-file docstring also refreshes the token mapping
conventions to use the current family-prefixed names
(`panel_border`, `text_dim`, `palette_series`, …) instead of the
pre-rename shorthand.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Two small follow-ups from review:

1. The `"splash"` preset alias went away — kept only `"default"` as the
   explicit name for the signature palette. Having two names for the
   same thing invites confusion in error messages and docs.

2. `KNOWN`, the `by_name` match arms, and the preset function
   definitions are all reordered alphabetically (catppuccin_mocha →
   default → dracula → gruvbox_dark → nord → tokyo_night). No
   positional meaning, easier to scan, same order everywhere a user
   or contributor encounters the list.

The alias-equivalence test is narrowed to just confirming `"default"`
matches `Theme::default()`; `presets::splash()` function is gone
since `Theme::default()` does the job inline now.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant