Skip to main content

ggen_core/codegen/
ux.rs

1//! UX Utilities - Progress indicators and user feedback
2//!
3//! This module provides user experience enhancements for the CLI:
4//! - Progress spinners and bars
5//! - Colored output formatting
6//! - Confirmation prompts
7//! - User-friendly messages
8
9use colored::Colorize;
10use indicatif::{ProgressBar, ProgressStyle};
11use std::io::{self, Write};
12use std::time::Duration;
13
14/// Progress indicator for long-running operations
15pub struct ProgressIndicator {
16    spinner: Option<ProgressBar>,
17    enabled: bool,
18}
19
20impl ProgressIndicator {
21    /// Create a new progress indicator
22    pub fn new(enabled: bool) -> Self {
23        Self {
24            spinner: None,
25            enabled,
26        }
27    }
28
29    /// Start a spinner with a message
30    pub fn start_spinner(&mut self, message: &str) {
31        if !self.enabled {
32            return;
33        }
34
35        let spinner = ProgressBar::new_spinner();
36        spinner.set_style(
37            ProgressStyle::default_spinner()
38                .tick_chars("⠁⠂⠄⡀⢀⠠⠐⠈ ")
39                .template("{spinner:.cyan} {msg}")
40                .unwrap_or_else(|_| ProgressStyle::default_spinner()),
41        );
42        spinner.set_message(message.to_string());
43        spinner.enable_steady_tick(Duration::from_millis(80));
44        self.spinner = Some(spinner);
45    }
46
47    /// Update the spinner message
48    pub fn update_message(&self, message: &str) {
49        if let Some(ref spinner) = self.spinner {
50            spinner.set_message(message.to_string());
51        }
52    }
53
54    /// Finish the spinner with a success message
55    pub fn finish_with_message(&mut self, message: &str) {
56        if let Some(spinner) = self.spinner.take() {
57            spinner.finish_with_message(format!("{} {}", "✓".green(), message));
58        }
59    }
60
61    /// Finish the spinner with an error message
62    pub fn finish_with_error(&mut self, message: &str) {
63        if let Some(spinner) = self.spinner.take() {
64            spinner.finish_with_message(format!("{} {}", "✗".red(), message));
65        }
66    }
67
68    /// Clear the spinner
69    pub fn clear(&mut self) {
70        if let Some(spinner) = self.spinner.take() {
71            spinner.finish_and_clear();
72        }
73    }
74}
75
76/// Progress bar for file generation
77pub struct FileProgressBar {
78    bar: Option<ProgressBar>,
79    #[allow(dead_code)]
80    enabled: bool,
81}
82
83impl FileProgressBar {
84    /// Create a new progress bar for file generation
85    pub fn new(total: usize, enabled: bool) -> Self {
86        if !enabled || total == 0 {
87            return Self {
88                bar: None,
89                enabled: false,
90            };
91        }
92
93        let bar = ProgressBar::new(total as u64);
94        bar.set_style(
95            ProgressStyle::default_bar()
96                .template("{spinner:.green} [{bar:40.cyan/blue}] {pos}/{len} {msg}")
97                .unwrap_or_else(|_| ProgressStyle::default_bar())
98                .progress_chars("#>-"),
99        );
100        Self {
101            bar: Some(bar),
102            enabled: true,
103        }
104    }
105
106    /// Increment the progress bar
107    pub fn inc(&self, delta: u64) {
108        if let Some(ref bar) = self.bar {
109            bar.inc(delta);
110        }
111    }
112
113    /// Set a message on the progress bar
114    pub fn set_message(&self, message: &str) {
115        if let Some(ref bar) = self.bar {
116            bar.set_message(message.to_string());
117        }
118    }
119
120    /// Finish the progress bar
121    pub fn finish(&mut self) {
122        if let Some(bar) = self.bar.take() {
123            bar.finish_and_clear();
124        }
125    }
126}
127
128/// Format a success message
129pub fn success_message(message: &str) -> String {
130    format!("{} {}", "✓".green().bold(), message)
131}
132
133/// Format an error message
134pub fn error_message(message: &str) -> String {
135    format!("{} {}", "✗".red().bold(), message)
136}
137
138/// Format a warning message
139pub fn warning_message(message: &str) -> String {
140    format!("{} {}", "⚠".yellow().bold(), message)
141}
142
143/// Format an info message
144pub fn info_message(message: &str) -> String {
145    format!("{} {}", "ℹ".blue().bold(), message)
146}
147
148/// Prompt user for yes/no confirmation
149///
150/// Returns `Ok(true)` if user confirms, `Ok(false)` if user declines,
151/// or `Err` if there's an I/O error.
152pub fn confirm_prompt(message: &str, default: bool) -> io::Result<bool> {
153    let default_text = if default { "[Y/n]" } else { "[y/N]" };
154    print!("{} {} {} ", "?".yellow().bold(), message, default_text);
155    io::stdout().flush()?;
156
157    let mut input = String::new();
158    io::stdin().read_line(&mut input)?;
159    let input = input.trim().to_lowercase();
160
161    Ok(match input.as_str() {
162        "" => default,
163        "y" | "yes" => true,
164        "n" | "no" => false,
165        _ => default,
166    })
167}
168
169/// Print a section header
170pub fn print_section(title: &str) {
171    eprintln!();
172    eprintln!("{}", title.cyan().bold());
173    eprintln!("{}", "─".repeat(title.len()).cyan());
174}
175
176/// Print a summary with statistics
177pub fn print_summary(title: &str, items: &[(&str, String)]) {
178    eprintln!();
179    eprintln!("{}", title.green().bold());
180    for (label, value) in items {
181        eprintln!("  {}: {}", label.bold(), value);
182    }
183}
184
185/// Format duration in human-readable format
186pub fn format_duration(duration_ms: u64) -> String {
187    let seconds = duration_ms as f64 / 1000.0;
188    if seconds < 1.0 {
189        format!("{}ms", duration_ms)
190    } else if seconds < 60.0 {
191        format!("{:.2}s", seconds)
192    } else {
193        let minutes = (seconds / 60.0).floor() as u64;
194        let secs = (seconds % 60.0).floor() as u64;
195        format!("{}m {}s", minutes, secs)
196    }
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202
203    #[test]
204    fn test_format_duration() {
205        assert_eq!(format_duration(500), "500ms");
206        assert_eq!(format_duration(1500), "1.50s");
207        assert_eq!(format_duration(65000), "1m 5s");
208    }
209
210    #[test]
211    fn test_message_formatting() {
212        let msg = success_message("Test");
213        assert!(msg.contains("Test"));
214
215        let msg = error_message("Error");
216        assert!(msg.contains("Error"));
217
218        let msg = warning_message("Warning");
219        assert!(msg.contains("Warning"));
220
221        let msg = info_message("Info");
222        assert!(msg.contains("Info"));
223    }
224}