use anyhow::Result;
use indicatif::{ProgressBar, ProgressStyle};
use std::io::IsTerminal;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
pub async fn show_loading_animation(cancel_flag: Arc<AtomicBool>, cost: f64) -> Result<()> {
let spinner = ProgressBar::new_spinner();
spinner.set_style(
ProgressStyle::default_spinner()
.template(" {spinner:.cyan} {msg:.cyan}")
.unwrap()
.tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧"),
);
let message = if cost > 0.0 {
format!("[~${cost:.2}] Generating response...")
} else {
"Generating response...".to_string()
};
spinner.set_message(message);
spinner.enable_steady_tick(Duration::from_millis(50));
while !cancel_flag.load(Ordering::SeqCst) {
tokio::time::sleep(Duration::from_millis(10)).await;
}
spinner.finish_and_clear();
Ok(())
}
pub async fn show_no_animation(cancel_flag: Arc<AtomicBool>, cost: f64) -> Result<()> {
if !std::io::stdin().is_terminal() {
println!(
" ── cost: ${:.5} ────────────────────────────────────────",
cost
);
}
while !cancel_flag.load(Ordering::SeqCst) {
tokio::time::sleep(Duration::from_millis(10)).await;
}
Ok(())
}
pub async fn show_smart_animation(cancel_flag: Arc<AtomicBool>, cost: f64) -> Result<()> {
if std::io::stdin().is_terminal() {
show_loading_animation(cancel_flag, cost).await
} else {
show_no_animation(cancel_flag, cost).await
}
}
pub fn show_generation_message_static(cost: f64) {
if !std::io::stdin().is_terminal() {
println!(
" ── cost: ${:.5} ────────────────────────────────────────",
cost
);
}
}