Skip to main content

memtui/ui/
theme.rs

1//! 2026 Modern Theme Module
2//! Clean, consistent styling with subtle animations
3//!
4//! Theme colors can be customized via `~/.config/memtui/theme.json`
5
6use ratatui::{
7    layout::Rect,
8    style::{Color, Modifier, Style},
9    text::{Line, Span},
10    widgets::{Block, BorderType, Borders},
11};
12use serde::{Deserialize, Serialize};
13use std::sync::atomic::{AtomicU8, Ordering};
14use std::sync::OnceLock;
15use std::time::{Duration, Instant};
16
17// ═══════════════════════════════════════════════════════════════════════════════
18// THEME CONFIGURATION
19// ═══════════════════════════════════════════════════════════════════════════════
20
21/// Global theme instance, loaded once at startup
22static THEME: OnceLock<ThemeConfig> = OnceLock::new();
23
24/// Get the current theme (loads default if not initialized)
25pub fn theme() -> &'static ThemeConfig {
26    THEME.get_or_init(ThemeConfig::default)
27}
28
29/// Initialize the global theme with a custom config
30/// Should be called once at startup before any rendering
31pub fn init_theme(config: ThemeConfig) {
32    let _ = THEME.set(config);
33}
34
35// ═══════════════════════════════════════════════════════════════════════════════
36// DIMMING SYSTEM
37// ═══════════════════════════════════════════════════════════════════════════════
38
39/// Current dim factor - only lives during a single render frame
40/// Using AtomicU8 for thread-safety (0-255 maps to 0.0-1.0)
41static DIM_FACTOR: AtomicU8 = AtomicU8::new(0);
42
43/// Apply dimming to all theme colors for this render frame.
44/// Call this at the start of render when a modal is active.
45/// The dim is automatically used by all color getters.
46pub fn dim_theme(factor: f32) {
47    let clamped = (factor.clamp(0.0, 1.0) * 255.0) as u8;
48    DIM_FACTOR.store(clamped, Ordering::Relaxed);
49}
50
51/// Restore theme to normal (no dimming).
52/// Call this at the end of render to ensure clean state.
53pub fn restore_theme() {
54    DIM_FACTOR.store(0, Ordering::Relaxed);
55}
56
57/// Get current dim factor (0.0 to 1.0)
58pub fn get_dim() -> f32 {
59    DIM_FACTOR.load(Ordering::Relaxed) as f32 / 255.0
60}
61
62/// Apply current dim factor to a color
63fn apply_dim(color: Color) -> Color {
64    let factor = get_dim();
65    if factor == 0.0 {
66        return color;
67    }
68    dim_color_by(color, factor)
69}
70
71/// Dim a color by a factor (0.0 = original, 1.0 = black)
72fn dim_color_by(color: Color, factor: f32) -> Color {
73    match color {
74        Color::Rgb(r, g, b) => {
75            let inv = 1.0 - factor;
76            Color::Rgb(
77                (r as f32 * inv) as u8,
78                (g as f32 * inv) as u8,
79                (b as f32 * inv) as u8,
80            )
81        }
82        // For non-RGB colors, we can't easily dim, return as-is
83        _ => color,
84    }
85}
86
87/// RGB color representation for JSON serialization
88#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
89pub struct RgbColor {
90    pub r: u8,
91    pub g: u8,
92    pub b: u8,
93}
94
95impl RgbColor {
96    pub const fn new(r: u8, g: u8, b: u8) -> Self {
97        Self { r, g, b }
98    }
99
100    pub fn to_color(self) -> Color {
101        Color::Rgb(self.r, self.g, self.b)
102    }
103}
104
105impl From<RgbColor> for Color {
106    fn from(rgb: RgbColor) -> Self {
107        rgb.to_color()
108    }
109}
110
111/// Complete theme configuration
112#[derive(Debug, Clone, Default, Serialize, Deserialize)]
113pub struct ThemeConfig {
114    /// Accent colors
115    #[serde(default)]
116    pub accent: AccentColors,
117
118    /// Neon/semantic colors
119    #[serde(default)]
120    pub neon: NeonColors,
121
122    /// Background colors
123    #[serde(default)]
124    pub background: BackgroundColors,
125
126    /// Text colors
127    #[serde(default)]
128    pub text: TextColors,
129
130    /// Border colors
131    #[serde(default)]
132    pub border: BorderColors,
133}
134
135/// Accent colors configuration
136#[derive(Debug, Clone, Serialize, Deserialize)]
137pub struct AccentColors {
138    /// Primary accent - cyan
139    #[serde(default = "default_accent")]
140    pub primary: RgbColor,
141    /// Secondary accent - lighter cyan
142    #[serde(default = "default_accent_dim")]
143    pub dim: RgbColor,
144    /// Highlight accent
145    #[serde(default = "default_accent_bright")]
146    pub bright: RgbColor,
147}
148
149impl Default for AccentColors {
150    fn default() -> Self {
151        Self {
152            primary: default_accent(),
153            dim: default_accent_dim(),
154            bright: default_accent_bright(),
155        }
156    }
157}
158
159/// Neon/semantic colors
160#[derive(Debug, Clone, Serialize, Deserialize)]
161pub struct NeonColors {
162    /// Green for success/connected
163    #[serde(default = "default_neon_green")]
164    pub green: RgbColor,
165    /// Amber for warnings
166    #[serde(default = "default_neon_amber")]
167    pub amber: RgbColor,
168    /// Red for errors
169    #[serde(default = "default_neon_red")]
170    pub red: RgbColor,
171    /// Purple for special elements
172    #[serde(default = "default_neon_purple")]
173    pub purple: RgbColor,
174    /// Cyan for accents
175    #[serde(default = "default_neon_cyan")]
176    pub cyan: RgbColor,
177    /// Pink for logo gradient
178    #[serde(default = "default_neon_pink")]
179    pub pink: RgbColor,
180    /// Electric blue
181    #[serde(default = "default_electric_blue")]
182    pub electric_blue: RgbColor,
183}
184
185impl Default for NeonColors {
186    fn default() -> Self {
187        Self {
188            green: default_neon_green(),
189            amber: default_neon_amber(),
190            red: default_neon_red(),
191            purple: default_neon_purple(),
192            cyan: default_neon_cyan(),
193            pink: default_neon_pink(),
194            electric_blue: default_electric_blue(),
195        }
196    }
197}
198
199/// Background colors
200#[derive(Debug, Clone, Serialize, Deserialize)]
201pub struct BackgroundColors {
202    /// Deep background
203    #[serde(default = "default_bg_deep")]
204    pub deep: RgbColor,
205    /// Panel background
206    #[serde(default = "default_bg_panel")]
207    pub panel: RgbColor,
208    /// Surface background - for cards/elevated areas
209    #[serde(default = "default_bg_surface")]
210    pub surface: RgbColor,
211    /// Selected item background
212    #[serde(default = "default_bg_selected")]
213    pub selected: RgbColor,
214    /// Elevated state
215    #[serde(default = "default_bg_elevated")]
216    pub elevated: RgbColor,
217    /// Hover state
218    #[serde(default = "default_bg_hover")]
219    pub hover: RgbColor,
220}
221
222impl Default for BackgroundColors {
223    fn default() -> Self {
224        Self {
225            deep: default_bg_deep(),
226            panel: default_bg_panel(),
227            surface: default_bg_surface(),
228            selected: default_bg_selected(),
229            elevated: default_bg_elevated(),
230            hover: default_bg_hover(),
231        }
232    }
233}
234
235/// Text colors
236#[derive(Debug, Clone, Serialize, Deserialize)]
237pub struct TextColors {
238    /// Dim text
239    #[serde(default = "default_text_dim")]
240    pub dim: RgbColor,
241    /// Secondary text
242    #[serde(default = "default_text_secondary")]
243    pub secondary: RgbColor,
244    /// Primary text
245    #[serde(default = "default_text_primary")]
246    pub primary: RgbColor,
247    /// Bright/white text
248    #[serde(default = "default_text_bright")]
249    pub bright: RgbColor,
250}
251
252impl Default for TextColors {
253    fn default() -> Self {
254        Self {
255            dim: default_text_dim(),
256            secondary: default_text_secondary(),
257            primary: default_text_primary(),
258            bright: default_text_bright(),
259        }
260    }
261}
262
263/// Border colors
264#[derive(Debug, Clone, Serialize, Deserialize)]
265pub struct BorderColors {
266    /// Dim border
267    #[serde(default = "default_border_dim")]
268    pub dim: RgbColor,
269    /// Active border
270    #[serde(default = "default_border_active")]
271    pub active: RgbColor,
272}
273
274impl Default for BorderColors {
275    fn default() -> Self {
276        Self {
277            dim: default_border_dim(),
278            active: default_border_active(),
279        }
280    }
281}
282
283// Default value functions
284fn default_accent() -> RgbColor {
285    RgbColor::new(80, 200, 220)
286}
287fn default_accent_dim() -> RgbColor {
288    RgbColor::new(60, 150, 170)
289}
290fn default_accent_bright() -> RgbColor {
291    RgbColor::new(100, 220, 240)
292}
293
294fn default_neon_green() -> RgbColor {
295    RgbColor::new(57, 255, 20)
296}
297fn default_neon_amber() -> RgbColor {
298    RgbColor::new(255, 191, 0)
299}
300fn default_neon_red() -> RgbColor {
301    RgbColor::new(255, 80, 80)
302}
303fn default_neon_purple() -> RgbColor {
304    RgbColor::new(160, 100, 220)
305}
306fn default_neon_cyan() -> RgbColor {
307    RgbColor::new(0, 255, 255)
308}
309fn default_neon_pink() -> RgbColor {
310    RgbColor::new(255, 100, 150)
311}
312fn default_electric_blue() -> RgbColor {
313    RgbColor::new(80, 180, 255)
314}
315
316fn default_bg_deep() -> RgbColor {
317    RgbColor::new(12, 14, 22)
318}
319fn default_bg_panel() -> RgbColor {
320    RgbColor::new(18, 21, 32)
321}
322fn default_bg_surface() -> RgbColor {
323    RgbColor::new(26, 30, 44)
324}
325fn default_bg_selected() -> RgbColor {
326    RgbColor::new(35, 45, 65)
327}
328fn default_bg_elevated() -> RgbColor {
329    RgbColor::new(40, 50, 70)
330}
331fn default_bg_hover() -> RgbColor {
332    RgbColor::new(45, 55, 75)
333}
334
335fn default_text_dim() -> RgbColor {
336    RgbColor::new(90, 100, 120)
337}
338fn default_text_secondary() -> RgbColor {
339    RgbColor::new(140, 150, 170)
340}
341fn default_text_primary() -> RgbColor {
342    RgbColor::new(210, 215, 230)
343}
344fn default_text_bright() -> RgbColor {
345    RgbColor::new(245, 248, 255)
346}
347
348fn default_border_dim() -> RgbColor {
349    RgbColor::new(50, 58, 78)
350}
351fn default_border_active() -> RgbColor {
352    RgbColor::new(80, 200, 220)
353}
354
355// ═══════════════════════════════════════════════════════════════════════════════
356// COLOR PALETTE (backward compatible functions that read from theme)
357// These use SCREAMING_CASE to match the original const-based API
358// All colors are automatically dimmed based on the global dim factor
359// ═══════════════════════════════════════════════════════════════════════════════
360
361#[allow(non_snake_case)]
362/// Primary accent - cyan
363pub fn ACCENT() -> Color {
364    apply_dim(theme().accent.primary.to_color())
365}
366#[allow(non_snake_case)]
367/// Secondary accent - lighter cyan
368pub fn ACCENT_DIM() -> Color {
369    apply_dim(theme().accent.dim.to_color())
370}
371#[allow(non_snake_case)]
372/// Highlight accent
373pub fn ACCENT_BRIGHT() -> Color {
374    apply_dim(theme().accent.bright.to_color())
375}
376
377#[allow(non_snake_case)]
378/// Neon green for success/connected
379pub fn NEON_GREEN() -> Color {
380    apply_dim(theme().neon.green.to_color())
381}
382#[allow(non_snake_case)]
383/// Amber for warnings
384pub fn NEON_AMBER() -> Color {
385    apply_dim(theme().neon.amber.to_color())
386}
387#[allow(non_snake_case)]
388/// Red for errors
389pub fn NEON_RED() -> Color {
390    apply_dim(theme().neon.red.to_color())
391}
392#[allow(non_snake_case)]
393/// Purple for special elements
394pub fn NEON_PURPLE() -> Color {
395    apply_dim(theme().neon.purple.to_color())
396}
397#[allow(non_snake_case)]
398/// Cyan for accents
399pub fn NEON_CYAN() -> Color {
400    apply_dim(theme().neon.cyan.to_color())
401}
402#[allow(non_snake_case)]
403/// Pink for logo gradient
404pub fn NEON_PINK() -> Color {
405    apply_dim(theme().neon.pink.to_color())
406}
407#[allow(non_snake_case)]
408/// Electric blue
409pub fn ELECTRIC_BLUE() -> Color {
410    apply_dim(theme().neon.electric_blue.to_color())
411}
412
413#[allow(non_snake_case)]
414/// Deep background
415pub fn BG_DEEP() -> Color {
416    apply_dim(theme().background.deep.to_color())
417}
418#[allow(non_snake_case)]
419/// Panel background
420pub fn BG_PANEL() -> Color {
421    apply_dim(theme().background.panel.to_color())
422}
423#[allow(non_snake_case)]
424/// Surface background - for cards/elevated areas
425pub fn BG_SURFACE() -> Color {
426    apply_dim(theme().background.surface.to_color())
427}
428#[allow(non_snake_case)]
429/// Selected item background
430pub fn BG_SELECTED() -> Color {
431    apply_dim(theme().background.selected.to_color())
432}
433#[allow(non_snake_case)]
434/// Hover/elevated state
435pub fn BG_ELEVATED() -> Color {
436    apply_dim(theme().background.elevated.to_color())
437}
438#[allow(non_snake_case)]
439pub fn BG_HOVER() -> Color {
440    apply_dim(theme().background.hover.to_color())
441}
442
443#[allow(non_snake_case)]
444/// Dim text
445pub fn TEXT_DIM() -> Color {
446    apply_dim(theme().text.dim.to_color())
447}
448#[allow(non_snake_case)]
449/// Secondary text
450pub fn TEXT_SECONDARY() -> Color {
451    apply_dim(theme().text.secondary.to_color())
452}
453#[allow(non_snake_case)]
454/// Primary text
455pub fn TEXT_PRIMARY() -> Color {
456    apply_dim(theme().text.primary.to_color())
457}
458#[allow(non_snake_case)]
459/// Bright/white text
460pub fn TEXT_BRIGHT() -> Color {
461    apply_dim(theme().text.bright.to_color())
462}
463
464#[allow(non_snake_case)]
465/// Border colors
466pub fn BORDER_DIM() -> Color {
467    apply_dim(theme().border.dim.to_color())
468}
469#[allow(non_snake_case)]
470pub fn BORDER_ACTIVE() -> Color {
471    apply_dim(theme().border.active.to_color())
472}
473
474// ═══════════════════════════════════════════════════════════════════════════════
475// RAW COLORS (undimmed - for modal content)
476// ═══════════════════════════════════════════════════════════════════════════════
477
478/// Raw colors module - bypasses dimming for modal/overlay content
479pub mod raw {
480    use super::*;
481
482    #[allow(non_snake_case)]
483    pub fn ACCENT() -> Color {
484        theme().accent.primary.to_color()
485    }
486    #[allow(non_snake_case)]
487    pub fn ACCENT_DIM() -> Color {
488        theme().accent.dim.to_color()
489    }
490    #[allow(non_snake_case)]
491    pub fn ACCENT_BRIGHT() -> Color {
492        theme().accent.bright.to_color()
493    }
494    #[allow(non_snake_case)]
495    pub fn NEON_GREEN() -> Color {
496        theme().neon.green.to_color()
497    }
498    #[allow(non_snake_case)]
499    pub fn NEON_AMBER() -> Color {
500        theme().neon.amber.to_color()
501    }
502    #[allow(non_snake_case)]
503    pub fn NEON_RED() -> Color {
504        theme().neon.red.to_color()
505    }
506    #[allow(non_snake_case)]
507    pub fn NEON_PURPLE() -> Color {
508        theme().neon.purple.to_color()
509    }
510    #[allow(non_snake_case)]
511    pub fn NEON_CYAN() -> Color {
512        theme().neon.cyan.to_color()
513    }
514    #[allow(non_snake_case)]
515    pub fn NEON_PINK() -> Color {
516        theme().neon.pink.to_color()
517    }
518    #[allow(non_snake_case)]
519    pub fn ELECTRIC_BLUE() -> Color {
520        theme().neon.electric_blue.to_color()
521    }
522    #[allow(non_snake_case)]
523    pub fn BG_DEEP() -> Color {
524        theme().background.deep.to_color()
525    }
526    #[allow(non_snake_case)]
527    pub fn BG_PANEL() -> Color {
528        theme().background.panel.to_color()
529    }
530    #[allow(non_snake_case)]
531    pub fn BG_SURFACE() -> Color {
532        theme().background.surface.to_color()
533    }
534    #[allow(non_snake_case)]
535    pub fn BG_SELECTED() -> Color {
536        theme().background.selected.to_color()
537    }
538    #[allow(non_snake_case)]
539    pub fn BG_ELEVATED() -> Color {
540        theme().background.elevated.to_color()
541    }
542    #[allow(non_snake_case)]
543    pub fn BG_HOVER() -> Color {
544        theme().background.hover.to_color()
545    }
546    #[allow(non_snake_case)]
547    pub fn TEXT_DIM() -> Color {
548        theme().text.dim.to_color()
549    }
550    #[allow(non_snake_case)]
551    pub fn TEXT_SECONDARY() -> Color {
552        theme().text.secondary.to_color()
553    }
554    #[allow(non_snake_case)]
555    pub fn TEXT_PRIMARY() -> Color {
556        theme().text.primary.to_color()
557    }
558    #[allow(non_snake_case)]
559    pub fn TEXT_BRIGHT() -> Color {
560        theme().text.bright.to_color()
561    }
562    #[allow(non_snake_case)]
563    pub fn BORDER_DIM() -> Color {
564        theme().border.dim.to_color()
565    }
566    #[allow(non_snake_case)]
567    pub fn BORDER_ACTIVE() -> Color {
568        theme().border.active.to_color()
569    }
570
571    // ─────────────────────────────────────────────────────────────────────────
572    // RAW STYLE HELPERS (for modal content)
573    // ─────────────────────────────────────────────────────────────────────────
574
575    /// Modal/dialog block using raw (undimmed) colors
576    pub fn modal_block(title: impl Into<String>) -> Block<'static> {
577        let title_str = title.into();
578        Block::default()
579            .title(format!(" {} ", title_str))
580            .title_style(
581                Style::default()
582                    .fg(TEXT_BRIGHT())
583                    .add_modifier(Modifier::BOLD),
584            )
585            .borders(Borders::ALL)
586            .border_type(BorderType::Rounded)
587            .border_style(Style::default().fg(BORDER_DIM()))
588            .style(Style::default().bg(BG_DEEP()))
589    }
590
591    /// Input field block for forms (raw colors)
592    pub fn input_block(label: impl Into<String>, is_focused: bool) -> Block<'static> {
593        let label_str = label.into();
594        if is_focused {
595            Block::default()
596                .title(format!(" {} ", label_str))
597                .title_style(
598                    Style::default()
599                        .fg(ACCENT_BRIGHT())
600                        .add_modifier(Modifier::BOLD),
601                )
602                .borders(Borders::ALL)
603                .border_type(BorderType::Rounded)
604                .border_style(Style::default().fg(ACCENT()))
605        } else {
606            Block::default()
607                .title(format!(" {} ", label_str))
608                .title_style(Style::default().fg(TEXT_DIM()))
609                .borders(Borders::ALL)
610                .border_type(BorderType::Rounded)
611                .border_style(Style::default().fg(BORDER_DIM()))
612        }
613    }
614
615    /// Form title style (raw)
616    pub fn form_title() -> Style {
617        Style::default()
618            .fg(NEON_CYAN())
619            .add_modifier(Modifier::BOLD)
620    }
621
622    /// Form hint style (raw)
623    pub fn form_hint() -> Style {
624        Style::default().fg(TEXT_DIM())
625    }
626
627    /// Form error style (raw)
628    pub fn form_error() -> Style {
629        Style::default().fg(NEON_RED())
630    }
631
632    /// Form note style (raw)
633    pub fn form_note() -> Style {
634        Style::default()
635            .fg(TEXT_DIM())
636            .add_modifier(Modifier::ITALIC)
637    }
638
639    /// Input text style (raw)
640    pub fn input_text() -> Style {
641        Style::default().fg(TEXT_PRIMARY())
642    }
643
644    /// Keybind key style (raw)
645    pub fn keybind_key_style() -> Style {
646        Style::default().fg(NEON_AMBER())
647    }
648
649    /// Selector option selected (raw)
650    pub fn selector_option_selected(is_field_active: bool) -> Style {
651        if is_field_active {
652            Style::default()
653                .fg(BG_DEEP())
654                .bg(ACCENT())
655                .add_modifier(Modifier::BOLD)
656        } else {
657            Style::default()
658                .fg(BG_DEEP())
659                .bg(TEXT_SECONDARY())
660                .add_modifier(Modifier::BOLD)
661        }
662    }
663
664    /// Selector option unselected (raw)
665    pub fn selector_option_unselected(is_field_active: bool) -> Style {
666        if is_field_active {
667            Style::default().fg(ACCENT_DIM())
668        } else {
669            Style::default().fg(TEXT_DIM())
670        }
671    }
672}
673
674// ═══════════════════════════════════════════════════════════════════════════════
675// ANIMATION STATE
676// ═══════════════════════════════════════════════════════════════════════════════
677
678/// Gradient color pair for logo
679#[derive(Clone, Copy)]
680pub struct GradientColors {
681    pub start: (u8, u8, u8),
682    pub end: (u8, u8, u8),
683}
684
685/// Subtle gradient presets - all pleasant color combinations
686const GRADIENT_PRESETS: &[GradientColors] = &[
687    // Cyan to Blue
688    GradientColors {
689        start: (0, 230, 255),
690        end: (60, 160, 255),
691    },
692    // Cyan to Teal
693    GradientColors {
694        start: (0, 230, 240),
695        end: (0, 180, 200),
696    },
697    // Blue to Purple
698    GradientColors {
699        start: (100, 180, 255),
700        end: (180, 130, 255),
701    },
702    // Teal to Cyan
703    GradientColors {
704        start: (0, 200, 200),
705        end: (80, 220, 255),
706    },
707    // Purple to Pink
708    GradientColors {
709        start: (160, 140, 255),
710        end: (220, 130, 200),
711    },
712    // Green to Cyan
713    GradientColors {
714        start: (80, 220, 180),
715        end: (0, 200, 230),
716    },
717    // Blue to Cyan
718    GradientColors {
719        start: (80, 160, 255),
720        end: (0, 220, 240),
721    },
722    // Pink to Purple
723    GradientColors {
724        start: (230, 140, 200),
725        end: (160, 120, 230),
726    },
727];
728
729#[derive(Clone)]
730pub struct AnimationState {
731    pub start_time: Instant,
732    pub gradient: GradientColors,
733}
734
735impl Default for AnimationState {
736    fn default() -> Self {
737        // Pick a random gradient based on current time
738        let seed = Instant::now().elapsed().as_nanos() as usize;
739        let gradient = GRADIENT_PRESETS[seed % GRADIENT_PRESETS.len()];
740
741        Self {
742            start_time: Instant::now(),
743            gradient,
744        }
745    }
746}
747
748impl AnimationState {
749    pub fn new() -> Self {
750        Self::default()
751    }
752
753    pub fn elapsed(&self) -> Duration {
754        self.start_time.elapsed()
755    }
756
757    /// Oscillates between 0.0 and 1.0
758    pub fn pulse(&self, period_ms: u64) -> f32 {
759        let elapsed_ms = self.elapsed().as_millis() as f32;
760        let period = period_ms as f32;
761        ((elapsed_ms / period * std::f32::consts::PI * 2.0).sin() + 1.0) / 2.0
762    }
763
764    /// Cycles through 0.0 to 1.0
765    pub fn cycle(&self, period_ms: u64) -> f32 {
766        let elapsed_ms = self.elapsed().as_millis() as u64;
767        (elapsed_ms % period_ms) as f32 / period_ms as f32
768    }
769
770    /// Returns animation frame index
771    pub fn frame(&self, frame_count: usize, period_ms: u64) -> usize {
772        let elapsed_ms = self.elapsed().as_millis() as u64;
773        ((elapsed_ms / period_ms) as usize) % frame_count
774    }
775}
776
777// ═══════════════════════════════════════════════════════════════════════════════
778// SPINNER/LOADING INDICATORS
779// ═══════════════════════════════════════════════════════════════════════════════
780
781pub const SPINNER_FRAMES: [&str; 8] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧"];
782pub const SPINNER_DOTS: [&str; 4] = ["⣾", "⣽", "⣻", "⢿"];
783pub const SPINNER_PULSE: [&str; 4] = ["◐", "◓", "◑", "◒"];
784
785pub fn spinner(animation: &AnimationState) -> &'static str {
786    let frame = animation.frame(SPINNER_FRAMES.len(), 100);
787    SPINNER_FRAMES[frame]
788}
789
790pub fn spinner_dots(animation: &AnimationState) -> &'static str {
791    let frame = animation.frame(SPINNER_DOTS.len(), 150);
792    SPINNER_DOTS[frame]
793}
794
795pub fn spinner_pulse(animation: &AnimationState) -> &'static str {
796    let frame = animation.frame(SPINNER_PULSE.len(), 250);
797    SPINNER_PULSE[frame]
798}
799
800/// Status indicators
801pub const INDICATOR_CONNECTED: &str = "●";
802pub const INDICATOR_CONNECTING: &str = "◐";
803pub const INDICATOR_DISCONNECTED: &str = "○";
804pub const INDICATOR_ERROR: &str = "✕";
805
806// ═══════════════════════════════════════════════════════════════════════════════
807// SCROLLBAR STYLES
808// ═══════════════════════════════════════════════════════════════════════════════
809
810use ratatui::widgets::{Scrollbar, ScrollbarOrientation};
811
812/// Create a consistently styled vertical scrollbar
813pub fn scrollbar(is_active: bool) -> Scrollbar<'static> {
814    Scrollbar::new(ScrollbarOrientation::VerticalRight)
815        .begin_symbol(Some("▲"))
816        .end_symbol(Some("▼"))
817        .track_symbol(Some("│"))
818        .thumb_symbol("█")
819        .style(Style::default().fg(if is_active {
820            ACCENT_DIM()
821        } else {
822            BORDER_DIM()
823        }))
824}
825
826/// Scrollbar area positioned at the right edge of a content area
827pub fn scrollbar_area(content_area: Rect) -> Rect {
828    Rect::new(
829        content_area.x + content_area.width.saturating_sub(1),
830        content_area.y,
831        1,
832        content_area.height,
833    )
834}
835
836// ═══════════════════════════════════════════════════════════════════════════════
837// BORDER STYLES
838// ═══════════════════════════════════════════════════════════════════════════════
839
840pub fn border_inactive() -> Style {
841    Style::default().fg(BORDER_DIM())
842}
843
844pub fn border_focused() -> Style {
845    Style::default().fg(BORDER_ACTIVE())
846}
847
848pub fn border_active(_animation: &AnimationState) -> Style {
849    border_focused()
850}
851
852// ═══════════════════════════════════════════════════════════════════════════════
853// STATUS STYLES
854// ═══════════════════════════════════════════════════════════════════════════════
855
856pub fn status_connected() -> Style {
857    Style::default().fg(NEON_GREEN())
858}
859
860pub fn status_connecting(animation: &AnimationState) -> Style {
861    let pulse = animation.pulse(800);
862    let intensity = (180.0 + 75.0 * pulse) as u8;
863    Style::default().fg(Color::Rgb(255, intensity, 0))
864}
865
866pub fn status_error() -> Style {
867    Style::default().fg(NEON_RED())
868}
869
870pub fn status_disconnected() -> Style {
871    Style::default().fg(TEXT_DIM())
872}
873
874// ═══════════════════════════════════════════════════════════════════════════════
875// BLOCK BUILDERS
876// ═══════════════════════════════════════════════════════════════════════════════
877
878/// Create a panel block - borderless, no title (header rendered separately)
879pub fn panel_block(_title: impl Into<String>, _is_active: bool) -> Block<'static> {
880    Block::default()
881        .borders(Borders::NONE)
882        .padding(ratatui::widgets::Padding::new(1, 1, 0, 0))
883}
884
885/// Render a full-width panel header line
886/// Returns the content area (below the header)
887pub fn render_panel_header(
888    f: &mut ratatui::Frame,
889    area: Rect,
890    title: &str,
891    is_active: bool,
892) -> Rect {
893    render_panel_header_split(f, area, title, "", is_active)
894}
895
896/// Render a full-width panel header with left title and right info
897/// Returns the content area (below the header)
898pub fn render_panel_header_split(
899    f: &mut ratatui::Frame,
900    area: Rect,
901    title_left: &str,
902    title_right: &str,
903    is_active: bool,
904) -> Rect {
905    let header_area = Rect::new(area.x, area.y, area.width, 1);
906    let content_area = Rect::new(
907        area.x,
908        area.y + 1,
909        area.width,
910        area.height.saturating_sub(1),
911    );
912
913    let (bg_color, fg_color, right_fg) = if is_active {
914        (ACCENT(), BG_DEEP(), BG_DEEP())
915    } else {
916        (BG_SURFACE(), TEXT_SECONDARY(), TEXT_DIM())
917    };
918
919    // Build content with exact width to fill header completely
920    let width = area.width as usize;
921    let left_content = format!(" {} ", title_left);
922    let left_len = left_content.chars().count();
923
924    let right_content = if title_right.is_empty() {
925        String::new()
926    } else {
927        format!("{} ", title_right)
928    };
929    let right_len = right_content.chars().count();
930
931    let padding = width.saturating_sub(left_len + right_len);
932
933    let mut spans = vec![
934        Span::styled(
935            left_content,
936            Style::default()
937                .fg(fg_color)
938                .bg(bg_color)
939                .add_modifier(Modifier::BOLD),
940        ),
941        Span::styled(" ".repeat(padding), Style::default().bg(bg_color)),
942    ];
943
944    if !title_right.is_empty() {
945        spans.push(Span::styled(
946            right_content,
947            Style::default().fg(right_fg).bg(bg_color),
948        ));
949    }
950
951    let header =
952        ratatui::widgets::Paragraph::new(Line::from(spans)).style(Style::default().bg(bg_color));
953    f.render_widget(header, header_area);
954
955    content_area
956}
957
958/// Alias for backwards compatibility
959pub fn themed_block(title: impl Into<String>, is_active: bool) -> Block<'static> {
960    panel_block(title, is_active)
961}
962
963pub fn animated_block(
964    title: impl Into<String>,
965    is_active: bool,
966    _animation: &AnimationState,
967) -> Block<'static> {
968    panel_block(title, is_active)
969}
970
971/// Modal/dialog block - for popups, dialogs, forms
972/// Has its own background since it floats above other content
973pub fn modal_block(title: impl Into<String>) -> Block<'static> {
974    let title_str = title.into();
975    Block::default()
976        .title(format!(" {} ", title_str))
977        .title_style(
978            Style::default()
979                .fg(TEXT_BRIGHT())
980                .add_modifier(Modifier::BOLD),
981        )
982        .borders(Borders::ALL)
983        .border_type(BorderType::Rounded)
984        .border_style(Style::default().fg(BORDER_DIM()))
985        .style(Style::default().bg(BG_DEEP()))
986}
987
988/// Glass-style block for dialogs (kept for compatibility)
989pub fn glass_block(title: impl Into<String>) -> Block<'static> {
990    modal_block(title)
991}
992
993/// Confirmation dialog block (quit, delete, etc.)
994/// Same style as modal_block for consistency
995pub fn confirm_block(title: impl Into<String>) -> Block<'static> {
996    modal_block(title)
997}
998
999// ═══════════════════════════════════════════════════════════════════════════════
1000// LIST/SELECTION STYLES
1001// ═══════════════════════════════════════════════════════════════════════════════
1002
1003/// Style for selected items - only sets background, preserves text colors
1004pub fn list_selected() -> Style {
1005    Style::default().bg(BG_SELECTED())
1006}
1007
1008/// Highlighted item (stronger selection indicator)
1009pub fn list_highlight() -> Style {
1010    Style::default()
1011        .bg(BG_ELEVATED())
1012        .add_modifier(Modifier::BOLD)
1013}
1014
1015pub fn list_hover() -> Style {
1016    Style::default().bg(BG_HOVER())
1017}
1018
1019pub fn text_highlight() -> Style {
1020    Style::default()
1021        .fg(ACCENT_BRIGHT())
1022        .add_modifier(Modifier::BOLD)
1023}
1024
1025// ═══════════════════════════════════════════════════════════════════════════════
1026// LAYOUT HELPERS
1027// ═══════════════════════════════════════════════════════════════════════════════
1028
1029#[derive(Clone, Copy)]
1030pub struct PaneSplit {
1031    pub ratio: f32,
1032    pub min: f32,
1033    pub max: f32,
1034    pub resizing: bool,
1035}
1036
1037impl Default for PaneSplit {
1038    fn default() -> Self {
1039        Self {
1040            ratio: 0.4,
1041            min: 0.2,
1042            max: 0.8,
1043            resizing: false,
1044        }
1045    }
1046}
1047
1048impl PaneSplit {
1049    pub fn new(ratio: f32) -> Self {
1050        Self {
1051            ratio: ratio.clamp(0.2, 0.8),
1052            ..Default::default()
1053        }
1054    }
1055
1056    pub fn adjust(&mut self, delta: f32) {
1057        self.ratio = (self.ratio + delta).clamp(self.min, self.max);
1058    }
1059
1060    pub fn left_percent(&self) -> u16 {
1061        (self.ratio * 100.0) as u16
1062    }
1063
1064    pub fn right_percent(&self) -> u16 {
1065        100 - self.left_percent()
1066    }
1067
1068    pub fn is_on_handle(&self, area: Rect, x: u16) -> bool {
1069        let split_x = area.x + (area.width as f32 * self.ratio) as u16;
1070        x >= split_x.saturating_sub(1) && x <= split_x.saturating_add(1)
1071    }
1072}
1073
1074// ═══════════════════════════════════════════════════════════════════════════════
1075// KEYBINDING DISPLAY
1076// ═══════════════════════════════════════════════════════════════════════════════
1077
1078pub fn keybind(key: &str, description: &str) -> Vec<Span<'static>> {
1079    vec![
1080        Span::styled(
1081            format!(" {} ", key),
1082            Style::default()
1083                .fg(BG_DEEP())
1084                .bg(ACCENT())
1085                .add_modifier(Modifier::BOLD),
1086        ),
1087        Span::styled(
1088            format!(" {} ", description),
1089            Style::default().fg(TEXT_SECONDARY()),
1090        ),
1091    ]
1092}
1093
1094pub fn keybind_subtle(key: &str, description: &str) -> Vec<Span<'static>> {
1095    vec![
1096        Span::styled(key.to_string(), Style::default().fg(NEON_AMBER())),
1097        Span::styled(
1098            format!(" {} ", description),
1099            Style::default().fg(TEXT_DIM()),
1100        ),
1101    ]
1102}
1103
1104/// Style for inline keybind hints (just the key part)
1105pub fn keybind_key_style() -> Style {
1106    Style::default().fg(NEON_AMBER())
1107}
1108
1109// ═══════════════════════════════════════════════════════════════════════════════
1110// LOGO
1111// ═══════════════════════════════════════════════════════════════════════════════
1112
1113pub const LOGO: &[&str] = &[
1114    "███╗   ███╗███████╗███╗   ███╗████████╗██╗   ██╗██╗",
1115    "████╗ ████║██╔════╝████╗ ████║╚══██╔══╝██║   ██║██║",
1116    "██╔████╔██║█████╗  ██╔████╔██║   ██║   ██║   ██║██║",
1117    "██║╚██╔╝██║██╔══╝  ██║╚██╔╝██║   ██║   ██║   ██║██║",
1118    "██║ ╚═╝ ██║███████╗██║ ╚═╝ ██║   ██║   ╚██████╔╝██║",
1119    "╚═╝     ╚═╝╚══════╝╚═╝     ╚═╝   ╚═╝    ╚═════╝ ╚═╝",
1120];
1121
1122pub const LOGO_COMPACT: &[&str] = &["┏┳┓┏━╸┏┳┓╺┳╸╻ ╻╻", "┃┃┃┣╸ ┃┃┃ ┃ ┃ ┃┃", "╹ ╹┗━╸╹ ╹ ╹ ┗━┛╹"];
1123
1124/// Create styled logo with smooth animated gradient (random colors each launch)
1125pub fn logo_lines(animation: &AnimationState) -> Vec<Line<'static>> {
1126    // 5 second cycle
1127    let cycle = animation.cycle(5000);
1128    let gradient = &animation.gradient;
1129
1130    LOGO.iter()
1131        .map(|line| {
1132            let char_count = line.chars().count() as f32;
1133
1134            let chars: Vec<Span<'static>> = line
1135                .chars()
1136                .enumerate()
1137                .map(|(char_idx, ch)| {
1138                    if ch == ' ' {
1139                        return Span::styled(ch.to_string(), Style::default());
1140                    }
1141
1142                    // Position along the line (0.0 to 1.0)
1143                    let pos = char_idx as f32 / char_count;
1144
1145                    // Smooth sine wave that travels across - no harsh edges
1146                    let wave = ((pos * std::f32::consts::PI * 2.0)
1147                        - (cycle * std::f32::consts::PI * 2.0))
1148                        .sin();
1149                    // Normalize from -1..1 to 0..1
1150                    let t = (wave + 1.0) / 2.0;
1151
1152                    // Interpolate between gradient start and end colors
1153                    let r = (gradient.start.0 as f32
1154                        + (gradient.end.0 as f32 - gradient.start.0 as f32) * t)
1155                        as u8;
1156                    let g = (gradient.start.1 as f32
1157                        + (gradient.end.1 as f32 - gradient.start.1 as f32) * t)
1158                        as u8;
1159                    let b = (gradient.start.2 as f32
1160                        + (gradient.end.2 as f32 - gradient.start.2 as f32) * t)
1161                        as u8;
1162
1163                    // Apply dimming to the computed color
1164                    let color = apply_dim(Color::Rgb(r, g, b));
1165
1166                    Span::styled(
1167                        ch.to_string(),
1168                        Style::default().fg(color).add_modifier(Modifier::BOLD),
1169                    )
1170                })
1171                .collect();
1172
1173            Line::from(chars)
1174        })
1175        .collect()
1176}
1177
1178// ═══════════════════════════════════════════════════════════════════════════════
1179// INPUT/FORM STYLES
1180// ═══════════════════════════════════════════════════════════════════════════════
1181
1182/// Input field block - for form text inputs
1183/// No background - inherits from parent
1184pub fn input_block(label: impl Into<String>, is_focused: bool) -> Block<'static> {
1185    let label_str = label.into();
1186    if is_focused {
1187        Block::default()
1188            .title(format!(" {} ", label_str))
1189            .title_style(
1190                Style::default()
1191                    .fg(ACCENT_BRIGHT())
1192                    .add_modifier(Modifier::BOLD),
1193            )
1194            .borders(Borders::ALL)
1195            .border_type(BorderType::Rounded)
1196            .border_style(Style::default().fg(ACCENT()))
1197    } else {
1198        Block::default()
1199            .title(format!(" {} ", label_str))
1200            .title_style(Style::default().fg(TEXT_DIM()))
1201            .borders(Borders::ALL)
1202            .border_type(BorderType::Rounded)
1203            .border_style(Style::default().fg(BORDER_DIM()))
1204    }
1205}
1206
1207/// Input text style
1208pub fn input_text() -> Style {
1209    Style::default().fg(TEXT_PRIMARY())
1210}
1211
1212/// Placeholder text style
1213pub fn input_placeholder() -> Style {
1214    Style::default().fg(TEXT_DIM())
1215}
1216
1217/// Style for selected option in a selector (e.g., backend type)
1218pub fn selector_option_selected(is_field_active: bool) -> Style {
1219    if is_field_active {
1220        Style::default()
1221            .fg(BG_DEEP())
1222            .bg(ACCENT())
1223            .add_modifier(Modifier::BOLD)
1224    } else {
1225        Style::default()
1226            .fg(BG_DEEP())
1227            .bg(TEXT_SECONDARY())
1228            .add_modifier(Modifier::BOLD)
1229    }
1230}
1231
1232/// Style for unselected option in a selector
1233pub fn selector_option_unselected(is_field_active: bool) -> Style {
1234    if is_field_active {
1235        Style::default().fg(ACCENT_DIM())
1236    } else {
1237        Style::default().fg(TEXT_DIM())
1238    }
1239}
1240
1241/// Form title style
1242pub fn form_title() -> Style {
1243    Style::default()
1244        .fg(NEON_CYAN())
1245        .add_modifier(Modifier::BOLD)
1246}
1247
1248/// Form instructions/hint style
1249pub fn form_hint() -> Style {
1250    Style::default().fg(TEXT_DIM())
1251}
1252
1253/// Form error style
1254pub fn form_error() -> Style {
1255    Style::default().fg(NEON_RED())
1256}
1257
1258/// Form note/info style
1259pub fn form_note() -> Style {
1260    Style::default()
1261        .fg(TEXT_DIM())
1262        .add_modifier(Modifier::ITALIC)
1263}
1264
1265// ═══════════════════════════════════════════════════════════════════════════════
1266// STATUS BAR STYLES
1267// ═══════════════════════════════════════════════════════════════════════════════
1268
1269/// Utility background for UI elements (status bar, tab bar, etc.)
1270pub fn util_bg() -> Style {
1271    Style::default().bg(BG_PANEL())
1272}
1273
1274/// Tab bar active tab style - same as active pane title but darker
1275pub fn tab_active() -> Style {
1276    Style::default()
1277        .fg(BG_DEEP())
1278        .bg(ACCENT_DIM())
1279        .add_modifier(Modifier::BOLD)
1280}
1281
1282/// Tab bar inactive style background (for the bar itself)
1283pub fn tab_inactive_bg() -> Color {
1284    BG_PANEL()
1285}
1286
1287/// Status indicator with symbol and color
1288pub fn status_indicator_connected() -> (&'static str, Style) {
1289    (INDICATOR_CONNECTED, Style::default().fg(NEON_GREEN()))
1290}
1291
1292pub fn status_indicator_connecting() -> (&'static str, Style) {
1293    (INDICATOR_CONNECTING, Style::default().fg(NEON_AMBER()))
1294}
1295
1296pub fn status_indicator_disconnected() -> (&'static str, Style) {
1297    (INDICATOR_DISCONNECTED, Style::default().fg(TEXT_DIM()))
1298}
1299
1300pub fn status_indicator_error() -> (&'static str, Style) {
1301    (INDICATOR_ERROR, Style::default().fg(NEON_RED()))
1302}
1303
1304/// Status bar hint text style
1305pub fn status_hint() -> Style {
1306    Style::default().fg(TEXT_DIM())
1307}
1308
1309/// Status bar operation indicator
1310pub fn status_operation() -> Style {
1311    Style::default().fg(NEON_CYAN())
1312}
1313
1314// ═══════════════════════════════════════════════════════════════════════════════
1315// MESSAGE STYLES (warnings, errors, toasts)
1316// ═══════════════════════════════════════════════════════════════════════════════
1317
1318/// Warning message style (icon and text)
1319pub fn message_warning() -> (Style, Style) {
1320    let style = Style::default().fg(NEON_AMBER());
1321    let bg = Style::default().bg(Color::Rgb(35, 30, 15));
1322    (style, bg)
1323}
1324
1325/// Error message style (icon and text)
1326pub fn message_error() -> (Style, Style) {
1327    let style = Style::default().fg(NEON_RED());
1328    let bg = Style::default().bg(Color::Rgb(35, 15, 15));
1329    (style, bg)
1330}
1331
1332/// Info message style
1333pub fn message_info() -> (Style, Style) {
1334    let style = Style::default().fg(NEON_CYAN());
1335    let bg = Style::default().bg(Color::Rgb(15, 25, 35));
1336    (style, bg)
1337}
1338
1339/// Success message style
1340pub fn message_success() -> (Style, Style) {
1341    let style = Style::default().fg(NEON_GREEN());
1342    let bg = Style::default().bg(Color::Rgb(15, 35, 20));
1343    (style, bg)
1344}
1345
1346// ═══════════════════════════════════════════════════════════════════════════════
1347// LAYOUT UTILITIES
1348// ═══════════════════════════════════════════════════════════════════════════════
1349
1350use ratatui::layout::{Constraint, Direction, Layout};
1351
1352/// Create a centered rectangle within the given area
1353pub fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
1354    let popup_layout = Layout::default()
1355        .direction(Direction::Vertical)
1356        .constraints([
1357            Constraint::Percentage((100 - percent_y) / 2),
1358            Constraint::Percentage(percent_y),
1359            Constraint::Percentage((100 - percent_y) / 2),
1360        ])
1361        .split(r);
1362
1363    Layout::default()
1364        .direction(Direction::Horizontal)
1365        .constraints([
1366            Constraint::Percentage((100 - percent_x) / 2),
1367            Constraint::Percentage(percent_x),
1368            Constraint::Percentage((100 - percent_x) / 2),
1369        ])
1370        .split(popup_layout[1])[1]
1371}
1372
1373/// Create a fixed-size centered rectangle
1374pub fn centered_rect_fixed(width: u16, height: u16, r: Rect) -> Rect {
1375    let x = r.x + r.width.saturating_sub(width) / 2;
1376    let y = r.y + r.height.saturating_sub(height) / 2;
1377    Rect::new(x, y, width.min(r.width), height.min(r.height))
1378}
1379
1380// ═══════════════════════════════════════════════════════════════════════════════
1381// UTILITY
1382// ═══════════════════════════════════════════════════════════════════════════════
1383
1384pub fn separator_line(width: u16) -> Line<'static> {
1385    let bar = "─".repeat(width as usize);
1386    Line::from(Span::styled(bar, Style::default().fg(BORDER_DIM())))
1387}