1use std::sync::OnceLock;
5
6fn is_tty() -> bool {
11 static TTY: OnceLock<bool> = OnceLock::new();
12 *TTY.get_or_init(|| {
13 #[cfg(unix)]
15 unsafe { libc::isatty(1) != 0 }
16 #[cfg(not(unix))]
17 false
18 })
19}
20
21pub fn bold(s: &str) -> String {
26 if is_tty() { format!("\x1b[1m{s}\x1b[0m") } else { s.to_owned() }
27}
28
29pub fn dim(s: &str) -> String {
30 if is_tty() { format!("\x1b[2m{s}\x1b[0m") } else { s.to_owned() }
31}
32
33pub fn green(s: &str) -> String {
34 if is_tty() { format!("\x1b[32m{s}\x1b[0m") } else { s.to_owned() }
35}
36
37pub fn yellow(s: &str) -> String {
38 if is_tty() { format!("\x1b[33m{s}\x1b[0m") } else { s.to_owned() }
39}
40
41pub fn red(s: &str) -> String {
42 if is_tty() { format!("\x1b[31m{s}\x1b[0m") } else { s.to_owned() }
43}
44
45pub fn cyan(s: &str) -> String {
46 if is_tty() { format!("\x1b[36m{s}\x1b[0m") } else { s.to_owned() }
47}
48
49pub fn bold_white(s: &str) -> String {
50 if is_tty() { format!("\x1b[1;97m{s}\x1b[0m") } else { s.to_owned() }
51}
52
53pub fn dark_green(s: &str) -> String {
55 if is_tty() { format!("\x1b[38;5;28m{s}\x1b[0m") } else { s.to_owned() }
56}
57
58pub fn green_bold(s: &str) -> String {
60 if is_tty() { format!("\x1b[1;32m{s}\x1b[0m") } else { s.to_owned() }
61}
62
63pub fn brand_green(s: &str) -> String {
65 if is_tty() { format!("\x1b[1;38;5;34m{s}\x1b[0m") } else { s.to_owned() }
66}
67
68pub const CHECK: &str = "✓";
73pub const CROSS: &str = "✗";
74pub const DOT: &str = "●";
75pub const EMPTY: &str = "○";
76pub const DASH: &str = "—";
77pub const ARROW: &str = "→";
78pub const DIAMOND: &str = "◆";
79
80pub fn rule(width: usize) -> String {
86 dim(&"─".repeat(width))
87}
88
89pub fn section(label: &str) {
91 let dashes = "─".repeat(44usize.saturating_sub(label.len() + 4));
92 println!(" {} {} {}", bold_white("◆"), bold(label), dim(&dashes));
93}
94
95pub fn fmt_duration_ms(ms: u64) -> String {
101 let secs = ms / 1000;
102 if secs == 0 {
103 return "0s".into();
104 }
105 let mins = secs / 60;
106 if mins == 0 {
107 return format!("{}s", secs);
108 }
109 let hours = mins / 60;
110 let rem_mins = mins % 60;
111 if hours == 0 {
112 return format!("{mins}m");
113 }
114 let days = hours / 24;
115 let rem_hours = hours % 24;
116 if days == 0 {
117 if rem_mins == 0 { format!("{hours}h") } else { format!("{hours}h {rem_mins}m") }
118 } else if rem_hours == 0 {
119 format!("{days}d")
120 } else {
121 format!("{days}d {rem_hours}h")
122 }
123}
124
125pub struct SelectItem {
131 pub label: String,
133 pub value: String,
135}
136
137pub fn select(prompt: &str, items: &[SelectItem], initial: usize) -> Option<String> {
146 use crossterm::{
147 cursor,
148 event::{self, Event, KeyCode, KeyModifiers},
149 execute,
150 terminal::{self, ClearType},
151 };
152 use std::io::{stdout, Write};
153
154 if items.is_empty() {
155 return None;
156 }
157
158 let mut selected = initial.min(items.len() - 1);
159 let mut stdout = stdout();
160
161 terminal::enable_raw_mode().ok()?;
163 execute!(stdout, cursor::Hide).ok();
164
165 let render = |sel: usize, out: &mut dyn Write| {
166 let _ = write!(out, "\r\n {prompt}\r\n\r\n");
168 for (i, item) in items.iter().enumerate() {
169 if i == sel {
170 let _ = write!(out, " \x1b[1;32m◆\x1b[0m \x1b[1m{}\x1b[0m\r\n", item.label);
171 } else {
172 let _ = write!(out, " {}\r\n", item.label);
173 }
174 }
175 let _ = write!(
176 out,
177 "\r\n \x1b[2m↑ ↓ navigate · enter select · esc cancel\x1b[0m\r\n",
178 );
179 let _ = out.flush();
180 };
181
182 let lines_drawn = items.len() + 5; render(selected, &mut stdout);
185
186 let result = loop {
187 match event::read() {
188 Ok(Event::Key(key)) => {
189 execute!(
191 stdout,
192 cursor::MoveUp(lines_drawn as u16),
193 cursor::MoveToColumn(0),
194 terminal::Clear(ClearType::FromCursorDown),
195 ).ok();
196
197 match (key.code, key.modifiers) {
198 (KeyCode::Char('c'), KeyModifiers::CONTROL) => break None,
199 (KeyCode::Esc, _) | (KeyCode::Char('q'), _) => break None,
200 (KeyCode::Up, _) | (KeyCode::Char('k'), _) => {
201 selected = if selected == 0 { items.len() - 1 } else { selected - 1 };
202 render(selected, &mut stdout);
203 }
204 (KeyCode::Down, _) | (KeyCode::Char('j'), _) => {
205 selected = (selected + 1) % items.len();
206 render(selected, &mut stdout);
207 }
208 (KeyCode::Char(c), _) if c.is_ascii_digit() => {
209 let n = c as usize - '0' as usize;
210 if n >= 1 && n <= items.len() {
211 selected = n - 1;
212 render(selected, &mut stdout);
213 }
214 }
215 (KeyCode::Enter, _) => {
216 execute!(
218 stdout,
219 cursor::MoveUp(lines_drawn as u16),
220 cursor::MoveToColumn(0),
221 terminal::Clear(ClearType::FromCursorDown),
222 ).ok();
223 break Some(items[selected].value.clone());
224 }
225 _ => { render(selected, &mut stdout); }
226 }
227 }
228 _ => {}
229 }
230 };
231
232 execute!(stdout, cursor::Show).ok();
233 terminal::disable_raw_mode().ok();
234 println!();
235 result
236}
237
238#[cfg(test)]
239mod tests {
240 use super::fmt_duration_ms;
241
242 #[test]
243 fn test_fmt_duration_ms() {
244 assert_eq!(fmt_duration_ms(0), "0s");
245 assert_eq!(fmt_duration_ms(500), "0s");
246 assert_eq!(fmt_duration_ms(1_000), "1s");
247 assert_eq!(fmt_duration_ms(45_000), "45s");
248 assert_eq!(fmt_duration_ms(59_000), "59s");
249 assert_eq!(fmt_duration_ms(60_000), "1m");
250 assert_eq!(fmt_duration_ms(90_000), "1m"); assert_eq!(fmt_duration_ms(30 * 60_000), "30m");
252 assert_eq!(fmt_duration_ms(60 * 60_000), "1h");
253 assert_eq!(fmt_duration_ms(90 * 60_000), "1h 30m");
254 assert_eq!(fmt_duration_ms(5 * 3600_000), "5h");
255 assert_eq!(fmt_duration_ms(5 * 3600_000 + 30 * 60_000), "5h 30m");
256 assert_eq!(fmt_duration_ms(24 * 3600_000), "1d");
257 assert_eq!(fmt_duration_ms(48 * 3600_000), "2d");
258 assert_eq!(fmt_duration_ms(25 * 3600_000), "1d 1h");
259 assert_eq!(fmt_duration_ms(7 * 24 * 3600_000), "7d");
260 }
261}
262
263pub fn fmt_tokens(n: u64) -> String {
265 if n >= 1_000_000 {
266 format!("{:.1}M", n as f64 / 1_000_000.0)
267 } else if n >= 10_000 {
268 format!("{}k", n / 1_000)
269 } else if n >= 1_000 {
270 format!("{:.1}k", n as f64 / 1_000.0)
271 } else {
272 format!("{n}")
273 }
274}