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 = "→";
78
79pub fn rule(width: usize) -> String {
85 dim(&"─".repeat(width))
86}
87
88pub fn section(label: &str) {
90 let header = format!("{} {} {}", dim("──"), bold(label), dim(&"─".repeat(44 - label.len())));
91 println!("{header}");
92}
93
94pub fn fmt_duration_ms(ms: u64) -> String {
100 let secs = ms / 1000;
101 if secs == 0 {
102 return "0s".into();
103 }
104 let mins = secs / 60;
105 if mins == 0 {
106 return format!("{}s", secs);
107 }
108 let hours = mins / 60;
109 let rem_mins = mins % 60;
110 if hours == 0 {
111 return format!("{mins}m");
112 }
113 let days = hours / 24;
114 let rem_hours = hours % 24;
115 if days == 0 {
116 if rem_mins == 0 { format!("{hours}h") } else { format!("{hours}h {rem_mins}m") }
117 } else if rem_hours == 0 {
118 format!("{days}d")
119 } else {
120 format!("{days}d {rem_hours}h")
121 }
122}
123
124pub struct SelectItem {
130 pub label: String,
132 pub value: String,
134}
135
136pub fn select(prompt: &str, items: &[SelectItem], initial: usize) -> Option<String> {
145 use crossterm::{
146 cursor,
147 event::{self, Event, KeyCode, KeyModifiers},
148 execute,
149 terminal::{self, ClearType},
150 };
151 use std::io::{stdout, Write};
152
153 if items.is_empty() {
154 return None;
155 }
156
157 let mut selected = initial.min(items.len() - 1);
158 let mut stdout = stdout();
159
160 terminal::enable_raw_mode().ok()?;
162 execute!(stdout, cursor::Hide).ok();
163
164 let render = |sel: usize, out: &mut dyn Write| {
165 let _ = write!(out, "\r\n {prompt}\r\n\r\n");
167 for (i, item) in items.iter().enumerate() {
168 if i == sel {
169 let _ = write!(out, " \x1b[1;36m▶\x1b[0m \x1b[1m{}\x1b[0m\r\n", item.label);
170 } else {
171 let _ = write!(out, " {}\r\n", item.label);
172 }
173 }
174 let _ = write!(
175 out,
176 "\r\n \x1b[2m↑ ↓ navigate · enter select · esc cancel\x1b[0m\r\n",
177 );
178 let _ = out.flush();
179 };
180
181 let lines_drawn = items.len() + 5; render(selected, &mut stdout);
184
185 let result = loop {
186 match event::read() {
187 Ok(Event::Key(key)) => {
188 execute!(
190 stdout,
191 cursor::MoveUp(lines_drawn as u16),
192 cursor::MoveToColumn(0),
193 terminal::Clear(ClearType::FromCursorDown),
194 ).ok();
195
196 match (key.code, key.modifiers) {
197 (KeyCode::Char('c'), KeyModifiers::CONTROL) => break None,
198 (KeyCode::Esc, _) | (KeyCode::Char('q'), _) => break None,
199 (KeyCode::Up, _) | (KeyCode::Char('k'), _) => {
200 selected = if selected == 0 { items.len() - 1 } else { selected - 1 };
201 render(selected, &mut stdout);
202 }
203 (KeyCode::Down, _) | (KeyCode::Char('j'), _) => {
204 selected = (selected + 1) % items.len();
205 render(selected, &mut stdout);
206 }
207 (KeyCode::Char(c), _) if c.is_ascii_digit() => {
208 let n = c as usize - '0' as usize;
209 if n >= 1 && n <= items.len() {
210 selected = n - 1;
211 render(selected, &mut stdout);
212 }
213 }
214 (KeyCode::Enter, _) => {
215 execute!(
217 stdout,
218 cursor::MoveUp(lines_drawn as u16),
219 cursor::MoveToColumn(0),
220 terminal::Clear(ClearType::FromCursorDown),
221 ).ok();
222 break Some(items[selected].value.clone());
223 }
224 _ => { render(selected, &mut stdout); }
225 }
226 }
227 _ => {}
228 }
229 };
230
231 execute!(stdout, cursor::Show).ok();
232 terminal::disable_raw_mode().ok();
233 println!();
234 result
235}
236
237#[cfg(test)]
238mod tests {
239 use super::fmt_duration_ms;
240
241 #[test]
242 fn test_fmt_duration_ms() {
243 assert_eq!(fmt_duration_ms(0), "0s");
244 assert_eq!(fmt_duration_ms(500), "0s");
245 assert_eq!(fmt_duration_ms(1_000), "1s");
246 assert_eq!(fmt_duration_ms(45_000), "45s");
247 assert_eq!(fmt_duration_ms(59_000), "59s");
248 assert_eq!(fmt_duration_ms(60_000), "1m");
249 assert_eq!(fmt_duration_ms(90_000), "1m"); assert_eq!(fmt_duration_ms(30 * 60_000), "30m");
251 assert_eq!(fmt_duration_ms(60 * 60_000), "1h");
252 assert_eq!(fmt_duration_ms(90 * 60_000), "1h 30m");
253 assert_eq!(fmt_duration_ms(5 * 3600_000), "5h");
254 assert_eq!(fmt_duration_ms(5 * 3600_000 + 30 * 60_000), "5h 30m");
255 assert_eq!(fmt_duration_ms(24 * 3600_000), "1d");
256 assert_eq!(fmt_duration_ms(48 * 3600_000), "2d");
257 assert_eq!(fmt_duration_ms(25 * 3600_000), "1d 1h");
258 assert_eq!(fmt_duration_ms(7 * 24 * 3600_000), "7d");
259 }
260}
261
262pub fn fmt_tokens(n: u64) -> String {
264 if n >= 1_000_000 {
265 format!("{:.1}M", n as f64 / 1_000_000.0)
266 } else if n >= 10_000 {
267 format!("{}k", n / 1_000)
268 } else if n >= 1_000 {
269 format!("{:.1}k", n as f64 / 1_000.0)
270 } else {
271 format!("{n}")
272 }
273}