ratatui-themekit 0.2.0

Semantic theme system for ratatui — 20 color slots, 11 built-in themes, ThemeExt builders, NO_COLOR support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! # ratatui-themekit
//!
//! Semantic theme system for [ratatui](https://ratatui.rs) applications.
//!
//! Instead of hardcoding `Color::Rgb(...)` throughout your TUI, define
//! semantic slots (`accent`, `success`, `error`, `text_dim`, etc.) and
//! let the active theme provide the concrete colors. Switch themes at
//! runtime with zero code changes.
//!
//! ## Quick Start
//!
//! ```rust
//! use ratatui::style::Style;
//! use ratatui_themekit::{Theme, CatppuccinMocha};
//!
//! let theme: &dyn Theme = &CatppuccinMocha;
//!
//! // Use semantic slots — never hardcode colors
//! let header_style = Style::default().fg(theme.accent());
//! let error_style = Style::default().fg(theme.error());
//! let dim_style = Style::default().fg(theme.text_dim());
//! ```
//!
//! ## Built-in Themes
//!
//! | Theme | ID | Description |
//! |-------|----|-------------|
//! | [`CatppuccinMocha`] | `catppuccin` | Warm dark with pastels |
//! | [`Dracula`] | `dracula` | Dark with vivid colors |
//! | [`Nord`] | `nord` | Arctic blue-gray |
//! | [`GruvboxDark`] | `gruvbox` | Retro warm dark |
//! | [`OneDark`] | `one-dark` | Atom's iconic theme |
//! | [`SolarizedDark`] | `solarized` | Precision dark |
//! | [`NoColor`] | `no-color` | `NO_COLOR` compliant (all reset) |
//!
//! ## Resolve by ID
//!
//! ```rust
//! use ratatui_themekit::resolve_theme;
//!
//! let theme = resolve_theme("dracula");
//! assert_eq!(theme.id(), "dracula");
//! ```
//!
//! ## `NO_COLOR` Support
//!
//! Respects the [NO_COLOR](https://no-color.org/) convention:
//!
//! ```rust
//! use ratatui_themekit::no_color_active;
//!
//! if no_color_active() {
//!     // All colors are Color::Reset — safe for pipes, CI, screen readers
//! }
//! ```
//!
//! ## Custom Themes
//!
//! Implement the [`Theme`] trait — only 15 required methods. The rest
//! have sensible defaults derived from the core slots.
//!
//! ```rust
//! use ratatui::style::Color;
//! use ratatui_themekit::Theme;
//!
//! struct MyTheme;
//!
//! impl Theme for MyTheme {
//!     fn name(&self) -> &str { "My Theme" }
//!     fn id(&self) -> &str { "my-theme" }
//!     fn accent(&self) -> Color { Color::Rgb(249, 115, 22) } // orange
//!     fn accent_dim(&self) -> Color { Color::Rgb(120, 80, 40) }
//!     fn text(&self) -> Color { Color::Rgb(220, 220, 220) }
//!     fn text_dim(&self) -> Color { Color::Rgb(120, 120, 120) }
//!     fn text_bright(&self) -> Color { Color::Rgb(255, 255, 255) }
//!     fn success(&self) -> Color { Color::Green }
//!     fn error(&self) -> Color { Color::Red }
//!     fn warning(&self) -> Color { Color::Yellow }
//!     fn info(&self) -> Color { Color::Cyan }
//!     fn diff_added(&self) -> Color { Color::Green }
//!     fn diff_removed(&self) -> Color { Color::Red }
//!     fn diff_context(&self) -> Color { Color::DarkGray }
//!     fn border(&self) -> Color { Color::DarkGray }
//!     fn surface(&self) -> Color { Color::Rgb(40, 40, 40) }
//! }
//! ```

pub mod builders;
mod custom;
mod themes;

use ratatui::style::Color;

// Re-export theme data type + all built-in theme constants
pub use themes::ThemeData;
#[allow(unused_imports)]
pub use themes::{
    CATPPUCCIN_MOCHA, DRACULA, GRUVBOX_DARK, NO_COLOR, NORD, ONE_DARK, ROSE_PINE, SOLARIZED_DARK,
    TAILWIND_DARK, TERMINAL_NATIVE, TOKYO_NIGHT,
};

/// `PascalCase` aliases for ergonomic usage: `let t = CatppuccinMocha;`
#[allow(non_upper_case_globals, missing_docs, clippy::wildcard_imports)]
mod aliases {
    use super::*;
    pub const CatppuccinMocha: ThemeData = CATPPUCCIN_MOCHA;
    pub const Dracula: ThemeData = DRACULA;
    pub const Nord: ThemeData = NORD;
    pub const GruvboxDark: ThemeData = GRUVBOX_DARK;
    pub const OneDark: ThemeData = ONE_DARK;
    pub const SolarizedDark: ThemeData = SOLARIZED_DARK;
    pub const TailwindDark: ThemeData = TAILWIND_DARK;
    pub const TokyoNight: ThemeData = TOKYO_NIGHT;
    pub const RosePine: ThemeData = ROSE_PINE;
    pub const TerminalNative: ThemeData = TERMINAL_NATIVE;
    pub const NoColor: ThemeData = NO_COLOR;
}
pub use aliases::*;

// Re-export custom theme (serde-powered user themes)
pub use custom::CustomTheme;

// Re-export builders (the Tailwind-like utilities)
pub use builders::ThemeExt;

// ── Theme trait ──────────────────────────────────────────────────

/// Semantic color contract for ratatui applications.
///
/// Define **what** each color means, not what RGB value it is.
/// Every render function uses these slots. Swap themes at runtime
/// and every widget updates automatically.
///
/// # Required methods (15)
///
/// Core identity + 13 color slots + surface. All other methods
/// have defaults derived from these.
///
/// # Derived methods (5+)
///
/// `block_*` and `indicator_*` methods derive from core slots.
/// Override them for fine-grained control.
pub trait Theme: Send + Sync {
    /// Human-readable theme name (e.g. `"Catppuccin Mocha"`).
    fn name(&self) -> &str;

    /// Short identifier for config files (e.g. `"catppuccin"`).
    fn id(&self) -> &str;

    // ── Brand ─────────────────────────────────────────────────

    /// Primary brand/accent color.
    fn accent(&self) -> Color;

    /// Secondary accent (less prominent highlights).
    fn accent_dim(&self) -> Color;

    // ── Text ──────────────────────────────────────────────────

    /// Default text color.
    fn text(&self) -> Color;

    /// Dimmed/muted text (timestamps, hints, inactive elements).
    fn text_dim(&self) -> Color;

    /// Bright text for emphasis (bold titles, active elements).
    fn text_bright(&self) -> Color;

    // ── Status ────────────────────────────────────────────────

    /// Success / passed / running.
    fn success(&self) -> Color;

    /// Error / failed.
    fn error(&self) -> Color;

    /// Warning / pending / in-progress.
    fn warning(&self) -> Color;

    /// Informational / neutral highlight.
    fn info(&self) -> Color;

    // ── Diff ──────────────────────────────────────────────────

    /// Lines added.
    fn diff_added(&self) -> Color;

    /// Lines removed.
    fn diff_removed(&self) -> Color;

    /// Context/unchanged lines.
    fn diff_context(&self) -> Color;

    // ── Structure ─────────────────────────────────────────────

    /// Border/separator color.
    fn border(&self) -> Color;

    /// Background highlight for focused/selected elements.
    fn surface(&self) -> Color;

    // ── Derived defaults (override for fine control) ──────────

    /// Color for file-read operations.
    fn block_file_read(&self) -> Color {
        self.text_dim()
    }

    /// Color for file-edit operations.
    fn block_file_edit(&self) -> Color {
        self.diff_added()
    }

    /// Color for command/shell operations.
    fn block_command(&self) -> Color {
        self.text_bright()
    }

    /// Color for thinking/reasoning indicators.
    fn block_thinking(&self) -> Color {
        self.text_dim()
    }

    /// Color for passed indicators.
    fn block_pass(&self) -> Color {
        self.success()
    }

    /// Color for failed indicators.
    fn block_fail(&self) -> Color {
        self.error()
    }

    /// Color for system messages.
    fn block_system(&self) -> Color {
        self.text_dim()
    }

    /// Pending indicator color.
    fn indicator_pending(&self) -> Color {
        self.text_dim()
    }

    /// Running indicator color.
    fn indicator_running(&self) -> Color {
        self.warning()
    }

    /// Passed indicator color.
    fn indicator_passed(&self) -> Color {
        self.success()
    }

    /// Failed indicator color.
    fn indicator_failed(&self) -> Color {
        self.error()
    }

    /// Skipped indicator color.
    fn indicator_skipped(&self) -> Color {
        self.text_dim()
    }
}

// ── Resolution helpers ──────────────────────────────────────────

/// Resolves a theme by its config ID string.
///
/// Returns the matching built-in theme, or falls back to
/// [`CatppuccinMocha`] for unknown IDs. If [`no_color_active()`]
/// returns true, always returns [`NoColor`].
#[must_use]
pub fn resolve_theme(id: &str) -> Box<dyn Theme> {
    if no_color_active() {
        return Box::new(NO_COLOR);
    }
    match id {
        "dracula" => Box::new(DRACULA),
        "nord" => Box::new(NORD),
        "gruvbox" => Box::new(GRUVBOX_DARK),
        "one-dark" => Box::new(ONE_DARK),
        "solarized" => Box::new(SOLARIZED_DARK),
        "tailwind" => Box::new(TAILWIND_DARK),
        "tokyo-night" => Box::new(TOKYO_NIGHT),
        "rose-pine" => Box::new(ROSE_PINE),
        "terminal" => Box::new(TERMINAL_NATIVE),
        "no-color" => Box::new(NO_COLOR),
        // "catppuccin" and any unknown ID → default theme
        _ => Box::new(CATPPUCCIN_MOCHA),
    }
}

/// Returns all built-in theme instances.
#[must_use]
pub fn builtin_themes() -> Vec<Box<dyn Theme>> {
    vec![
        Box::new(CATPPUCCIN_MOCHA),
        Box::new(DRACULA),
        Box::new(NORD),
        Box::new(GRUVBOX_DARK),
        Box::new(ONE_DARK),
        Box::new(SOLARIZED_DARK),
        Box::new(TAILWIND_DARK),
        Box::new(TOKYO_NIGHT),
        Box::new(ROSE_PINE),
        Box::new(TERMINAL_NATIVE),
    ]
}

/// Returns all built-in theme IDs.
#[must_use]
pub fn available_theme_ids() -> Vec<&'static str> {
    vec![
        "catppuccin",
        "dracula",
        "nord",
        "gruvbox",
        "one-dark",
        "solarized",
        "tailwind",
        "tokyo-night",
        "rose-pine",
        "terminal",
    ]
}

/// Checks if the `NO_COLOR` environment variable is set.
///
/// Respects <https://no-color.org/>. When active, all colors should
/// be `Color::Reset` for accessibility (pipes, CI, screen readers).
#[must_use]
pub fn no_color_active() -> bool {
    std::env::var_os("NO_COLOR").is_some()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn resolve_known_theme() {
        let theme = resolve_theme("dracula");
        assert_eq!(theme.id(), "dracula");
        assert_eq!(theme.name(), "Dracula");
    }

    #[test]
    fn resolve_unknown_falls_back() {
        let theme = resolve_theme("nonexistent");
        assert_eq!(theme.id(), "catppuccin");
    }

    #[test]
    fn all_builtin_themes_have_unique_ids() {
        let themes = builtin_themes();
        let ids: Vec<&str> = themes.iter().map(|t| t.id()).collect();
        let mut dedup = ids.clone();
        dedup.sort_unstable();
        dedup.dedup();
        assert_eq!(ids.len(), dedup.len());
    }

    #[test]
    fn available_ids_match_builtins() {
        let ids = available_theme_ids();
        let themes = builtin_themes();
        assert_eq!(ids.len(), themes.len());
        for (id, theme) in ids.iter().zip(themes.iter()) {
            assert_eq!(*id, theme.id());
        }
    }

    #[test]
    fn derived_methods_use_core_slots() {
        let t = CatppuccinMocha;
        assert_eq!(t.block_pass(), t.success());
        assert_eq!(t.block_fail(), t.error());
        assert_eq!(t.block_file_read(), t.text_dim());
        assert_eq!(t.indicator_passed(), t.success());
        assert_eq!(t.indicator_failed(), t.error());
    }

    #[test]
    fn no_color_theme_is_all_reset() {
        let t = NoColor;
        assert_eq!(t.accent(), ratatui::style::Color::Reset);
        assert_eq!(t.text(), ratatui::style::Color::Reset);
        assert_eq!(t.error(), ratatui::style::Color::Reset);
        assert_eq!(t.border(), ratatui::style::Color::Reset);
    }

    #[test]
    fn every_builtin_has_distinct_status_colors() {
        for theme in builtin_themes() {
            assert_ne!(
                theme.success(),
                theme.error(),
                "theme '{}' has same success and error",
                theme.id()
            );
        }
    }

    #[test]
    fn every_builtin_has_distinct_diff_colors() {
        for theme in builtin_themes() {
            assert_ne!(
                theme.diff_added(),
                theme.diff_removed(),
                "theme '{}' has same diff_added and diff_removed",
                theme.id()
            );
        }
    }

    #[test]
    fn terminal_native_uses_named_colors() {
        let t = TerminalNative;
        assert_eq!(t.success(), ratatui::style::Color::Green);
        assert_eq!(t.error(), ratatui::style::Color::Red);
        assert_eq!(t.accent(), ratatui::style::Color::Blue);
    }

    #[test]
    fn tailwind_dark_uses_palette_constants() {
        let t = TailwindDark;
        // Tailwind colors are RGB — just verify they're not Reset or named
        assert_ne!(t.accent(), ratatui::style::Color::Reset);
        assert_ne!(t.success(), ratatui::style::Color::Reset);
    }

    #[test]
    fn resolve_all_known_ids() {
        for id in available_theme_ids() {
            let theme = resolve_theme(id);
            assert_eq!(theme.id(), id, "resolve_theme({id}) returned wrong theme");
        }
    }

    #[test]
    fn every_builtin_has_non_empty_name_and_id() {
        for theme in builtin_themes() {
            assert!(!theme.name().is_empty(), "theme name must not be empty");
            assert!(!theme.id().is_empty(), "theme id must not be empty");
            assert!(
                !theme.id().contains(' '),
                "theme id '{}' must not contain spaces",
                theme.id()
            );
        }
    }

    #[test]
    fn every_builtin_surface_differs_from_text() {
        for theme in builtin_themes() {
            assert_ne!(
                theme.surface(),
                theme.text(),
                "theme '{}' has same surface and text — focus highlight would be invisible",
                theme.id()
            );
        }
    }

    #[test]
    fn resolve_empty_string_falls_back() {
        let theme = resolve_theme("");
        assert_eq!(theme.id(), "catppuccin");
    }

    #[test]
    fn custom_theme_implements_trait() {
        let custom = CustomTheme {
            name: "Test".to_owned(),
            id: "test".to_owned(),
            accent: ratatui::style::Color::Magenta,
            accent_dim: ratatui::style::Color::DarkGray,
            text: ratatui::style::Color::White,
            text_dim: ratatui::style::Color::Gray,
            text_bright: ratatui::style::Color::White,
            success: ratatui::style::Color::Green,
            error: ratatui::style::Color::Red,
            warning: ratatui::style::Color::Yellow,
            info: ratatui::style::Color::Cyan,
            diff_added: ratatui::style::Color::Green,
            diff_removed: ratatui::style::Color::Red,
            diff_context: ratatui::style::Color::DarkGray,
            border: ratatui::style::Color::DarkGray,
            surface: ratatui::style::Color::Black,
        };
        let theme: &dyn Theme = &custom;
        assert_eq!(theme.name(), "Test");
        assert_eq!(theme.id(), "test");
        assert_eq!(theme.accent(), ratatui::style::Color::Magenta);
        // Derived methods work
        assert_eq!(theme.block_pass(), theme.success());
    }
}