Skip to main content

pandora_kit/
badge.rs

1use hefesto_widgets::{Badge, BadgeAnchor, BadgeStack, PopupSize};
2use ratatui::style::Color;
3
4// ─── CLI args ─────────────────────────────────────────────
5
6#[derive(clap::Args)]
7pub struct BadgeArgs {
8    /// Badge (repeatable). Format: `text|color|anchor[@L]|WxL`
9    #[arg(long = "badge", value_name = "TEXT|COLOR|ANCHOR|WxL")]
10    pub badges: Vec<String>,
11
12    /// Default badge width (0 = auto per-badge)
13    #[arg(long, default_value = "0")]
14    pub badge_width: u16,
15
16    /// Default content lines for each badge (default: 1)
17    #[arg(long, default_value = "1")]
18    pub badge_lines: u16,
19
20    /// Default anchor: tl, t, tr, bl, b, br, l, r (default: tl)
21    #[arg(long, default_value = "tl")]
22    pub badge_anchor: String,
23}
24
25impl BadgeArgs {
26    pub fn prepare_specs(&self) -> Vec<BadgeSpec> {
27        let global_anchor = parse_anchor(&self.badge_anchor).unwrap_or(BadgeAnchor::TopLeft);
28        let global_width = if self.badge_width > 0 { Some(DimMode::Fixed(self.badge_width)) } else { None };
29        self.badges.iter()
30            .map(|s| prepare_badge(parse_badge_arg(s), global_anchor, self.badge_lines, global_width))
31            .collect()
32    }
33}
34
35// ─── Types ────────────────────────────────────────────────
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum DimMode {
39    Auto,
40    Max(u16),
41    Fixed(u16),
42}
43
44pub struct BadgeParts {
45    pub text: String,
46    pub color: Color,
47    pub anchor: Option<BadgeAnchor>,
48    pub layer: Option<u16>,
49    pub width: Option<DimMode>,
50    pub lines: Option<DimMode>,
51}
52
53pub struct BadgeSpec {
54    pub display: String,
55    pub color: Color,
56    pub badge_w: u16,
57    pub lines: u16,
58    pub anchor: BadgeAnchor,
59    pub layer: u16,
60}
61
62impl BadgeSpec {
63    pub fn into_badge(&self) -> Badge<'_> {
64        let mut badge = if self.lines > 1 && self.display.contains('\n') {
65            let lines: Vec<ratatui::text::Line<'_>> =
66                self.display.split('\n').map(ratatui::text::Line::from).collect();
67            Badge::with_content(lines, self.color)
68                .width(PopupSize::Fixed(self.badge_w))
69                .height(PopupSize::Fixed(self.lines + 2))
70                .closable(false)
71        } else {
72            Badge::new(&self.display, self.color)
73                .width(PopupSize::Fixed(self.badge_w))
74                .height(PopupSize::Fixed(self.lines + 2))
75                .closable(false)
76        };
77        badge = badge.anchor(self.anchor).layer(self.layer);
78        badge
79    }
80}
81
82// ─── Parsing ─────────────────────────────────────────────
83
84pub fn parse_color(s: &str) -> Option<Color> {
85    match s.to_lowercase().as_str() {
86        "green" => Some(Color::Green),
87        "red" => Some(Color::Red),
88        "yellow" => Some(Color::Yellow),
89        "blue" => Some(Color::Blue),
90        "cyan" => Some(Color::Cyan),
91        "magenta" => Some(Color::Magenta),
92        "white" => Some(Color::White),
93        "black" => Some(Color::Black),
94        "gray" | "grey" => Some(Color::Gray),
95        "darkgray" | "darkgrey" => Some(Color::DarkGray),
96        "lightred" => Some(Color::LightRed),
97        "lightgreen" => Some(Color::LightGreen),
98        "lightyellow" => Some(Color::LightYellow),
99        "lightblue" => Some(Color::LightBlue),
100        "lightmagenta" => Some(Color::LightMagenta),
101        "lightcyan" => Some(Color::LightCyan),
102        _ => None,
103    }
104}
105
106pub fn parse_anchor(s: &str) -> Option<BadgeAnchor> {
107    match s.to_lowercase().as_str() {
108        "tl" | "top-left" => Some(BadgeAnchor::TopLeft),
109        "t" | "top" => Some(BadgeAnchor::Top),
110        "tr" | "top-right" => Some(BadgeAnchor::TopRight),
111        "bl" | "bottom-left" => Some(BadgeAnchor::BottomLeft),
112        "b" | "bottom" => Some(BadgeAnchor::Bottom),
113        "br" | "bottom-right" => Some(BadgeAnchor::BottomRight),
114        "l" | "left" => Some(BadgeAnchor::Left),
115        "r" | "right" => Some(BadgeAnchor::Right),
116        _ => None,
117    }
118}
119
120pub fn parse_anchor_and_layer(s: &str) -> (Option<BadgeAnchor>, Option<u16>) {
121    if let Some((anchor_part, layer_part)) = s.split_once('@') {
122        (parse_anchor(anchor_part), layer_part.parse::<u16>().ok())
123    } else {
124        (parse_anchor(s), None)
125    }
126}
127
128fn parse_dim(s: &str) -> Option<DimMode> {
129    if s.is_empty() || s.eq_ignore_ascii_case("a") {
130        Some(DimMode::Auto)
131    } else if let Some(rest) = s.strip_suffix(['a', 'A']) {
132        rest.parse::<u16>().ok().map(DimMode::Max)
133    } else {
134        s.parse::<u16>().ok().map(DimMode::Fixed)
135    }
136}
137
138pub fn parse_dimensions(s: &str) -> (Option<DimMode>, Option<DimMode>) {
139    if s.is_empty() {
140        return (None, None);
141    }
142    if let Some((w, l)) = s.split_once('x') {
143        let w = if w.is_empty() { Some(DimMode::Auto) } else { parse_dim(w) };
144        let l = if l.is_empty() { Some(DimMode::Auto) } else { parse_dim(l) };
145        (w, l)
146    } else {
147        (parse_dim(s), None)
148    }
149}
150
151pub fn parse_badge_arg(s: &str) -> BadgeParts {
152    let parts: Vec<&str> = s.split('|').collect();
153    let (anchor, layer) = parts.get(2).map(|a| parse_anchor_and_layer(a)).unwrap_or((None, None));
154
155    BadgeParts {
156        text: parts[0].to_string(),
157        color: parts.get(1).and_then(|c| parse_color(c)).unwrap_or(Color::Gray),
158        anchor,
159        layer,
160        width: parts.get(3).and_then(|d| parse_dimensions(d).0),
161        lines: parts.get(3).and_then(|d| parse_dimensions(d).1),
162    }
163}
164
165// ─── Text fitting ────────────────────────────────────────
166
167fn truncate_with_ellipsis(text: &str, max_len: usize) -> String {
168    if text.len() <= max_len {
169        return text.to_string();
170    }
171    let mut t: String = text.chars().take(max_len.saturating_sub(1)).collect();
172    t.push('…');
173    t
174}
175
176fn wrap_text(text: &str, content_w: usize, max_lines: u16) -> String {
177    let mut result = String::new();
178    let mut remaining = text;
179    for i in 0..max_lines as usize {
180        if remaining.is_empty() { break; }
181        let chunk_len = remaining.len().min(content_w);
182        let (chunk, rest) = remaining.split_at(chunk_len);
183        if i > 0 { result.push('\n'); }
184        if i == max_lines as usize - 1 && !rest.is_empty() {
185            let mut t: String = chunk.chars().take(content_w.saturating_sub(1)).collect();
186            t.push('…');
187            result.push_str(&t);
188        } else {
189            result.push_str(chunk);
190        }
191        remaining = rest;
192    }
193    result
194}
195
196// ─── Building ────────────────────────────────────────────
197
198fn resolve_width(dim: Option<DimMode>, global: Option<DimMode>, text_len: u16) -> u16 {
199    match dim.or(global).unwrap_or(DimMode::Auto) {
200        DimMode::Fixed(w) => w,
201        DimMode::Max(w) => (text_len + 2).min(w),
202        DimMode::Auto => text_len + 2,
203    }
204}
205
206fn resolve_lines(dim: Option<DimMode>, global_lines: u16) -> u16 {
207    match dim {
208        Some(DimMode::Fixed(n)) => n,
209        Some(DimMode::Max(n)) => n,
210        Some(DimMode::Auto) => global_lines,
211        None => global_lines,
212    }
213}
214
215pub fn prepare_badge(
216    parts: BadgeParts,
217    global_anchor: BadgeAnchor,
218    global_lines: u16,
219    global_width: Option<DimMode>,
220) -> BadgeSpec {
221    let anchor = parts.anchor.unwrap_or(global_anchor);
222    let layer = parts.layer.unwrap_or(0);
223    let lines = resolve_lines(parts.lines, global_lines);
224    let badge_w = resolve_width(parts.width, global_width, parts.text.len() as u16);
225    let content_w = badge_w.saturating_sub(2) as usize;
226
227    let display = if parts.text.len() <= content_w {
228        parts.text.to_string()
229    } else if lines > 1 {
230        wrap_text(&parts.text, content_w, lines)
231    } else {
232        truncate_with_ellipsis(&parts.text, content_w)
233    };
234
235    BadgeSpec { display, color: parts.color, badge_w, lines, anchor, layer }
236}
237
238pub fn build_badge_stack(specs: &[BadgeSpec]) -> BadgeStack<'_> {
239    let mut stack = BadgeStack::new();
240    for spec in specs {
241        stack = stack.push(spec.into_badge());
242    }
243    stack
244}
245
246// ─── Tests ───────────────────────────────────────────────
247
248#[cfg(test)]
249mod tests {
250    use super::*;
251
252    // ── parse_color ──
253
254    #[test]
255    fn parse_color_green() {
256        assert_eq!(parse_color("green"), Some(Color::Green));
257    }
258
259    #[test]
260    fn parse_color_case_insensitive() {
261        assert_eq!(parse_color("RED"), Some(Color::Red));
262        assert_eq!(parse_color("Cyan"), Some(Color::Cyan));
263    }
264
265    #[test]
266    fn parse_color_unknown_returns_none() {
267        assert_eq!(parse_color("pink"), None);
268        assert_eq!(parse_color(""), None);
269    }
270
271    #[test]
272    fn parse_color_gray_aliases() {
273        assert_eq!(parse_color("gray"), Some(Color::Gray));
274        assert_eq!(parse_color("grey"), Some(Color::Gray));
275    }
276
277    // ── parse_anchor ──
278
279    #[test]
280    fn parse_anchor_tl() {
281        assert_eq!(parse_anchor("tl"), Some(BadgeAnchor::TopLeft));
282    }
283
284    #[test]
285    fn parse_anchor_tr() {
286        assert_eq!(parse_anchor("tr"), Some(BadgeAnchor::TopRight));
287    }
288
289    #[test]
290    fn parse_anchor_bl() {
291        assert_eq!(parse_anchor("bl"), Some(BadgeAnchor::BottomLeft));
292    }
293
294    #[test]
295    fn parse_anchor_br() {
296        assert_eq!(parse_anchor("br"), Some(BadgeAnchor::BottomRight));
297    }
298
299    #[test]
300    fn parse_anchor_invalid() {
301        assert_eq!(parse_anchor("xyz"), None);
302    }
303
304    // ── parse_anchor_and_layer ──
305
306    #[test]
307    fn parse_anchor_only() {
308        let (a, l) = parse_anchor_and_layer("tl");
309        assert_eq!(a, Some(BadgeAnchor::TopLeft));
310        assert!(l.is_none());
311    }
312
313    #[test]
314    fn parse_anchor_with_layer() {
315        let (a, l) = parse_anchor_and_layer("tr@1");
316        assert_eq!(a, Some(BadgeAnchor::TopRight));
317        assert_eq!(l, Some(1));
318    }
319
320    #[test]
321    fn parse_anchor_with_layer_two() {
322        let (a, l) = parse_anchor_and_layer("bl@2");
323        assert_eq!(a, Some(BadgeAnchor::BottomLeft));
324        assert_eq!(l, Some(2));
325    }
326
327    #[test]
328    fn parse_anchor_invalid_layer_defaults() {
329        let (a, l) = parse_anchor_and_layer("tr@abc");
330        assert_eq!(a, Some(BadgeAnchor::TopRight));
331        assert!(l.is_none());
332    }
333
334    // ── parse_dimensions ──
335
336    #[test]
337    fn parse_dim_width_only() {
338        let (w, l) = parse_dimensions("20");
339        assert_eq!(w, Some(DimMode::Fixed(20)));
340        assert!(l.is_none());
341    }
342
343    #[test]
344    fn parse_dim_width_and_lines() {
345        let (w, l) = parse_dimensions("20x2");
346        assert_eq!(w, Some(DimMode::Fixed(20)));
347        assert_eq!(l, Some(DimMode::Fixed(2)));
348    }
349
350    #[test]
351    fn parse_dim_auto_up_to() {
352        let (w, l) = parse_dimensions("20a");
353        assert_eq!(w, Some(DimMode::Max(20)));
354        assert!(l.is_none());
355    }
356
357    #[test]
358    fn parse_dim_full_auto() {
359        let (w, l) = parse_dimensions("a");
360        assert_eq!(w, Some(DimMode::Auto));
361        assert!(l.is_none());
362    }
363
364    #[test]
365    fn parse_dim_both_auto_up_to() {
366        let (w, l) = parse_dimensions("20ax3a");
367        assert_eq!(w, Some(DimMode::Max(20)));
368        assert_eq!(l, Some(DimMode::Max(3)));
369    }
370
371    // ── parse_badge_arg ──
372
373    #[test]
374    fn parse_badge_arg_text_only() {
375        let p = parse_badge_arg("main");
376        assert_eq!(p.text, "main");
377        assert_eq!(p.color, Color::Gray);
378        assert!(p.anchor.is_none());
379        assert!(p.layer.is_none());
380        assert!(p.width.is_none());
381        assert!(p.lines.is_none());
382    }
383
384    #[test]
385    fn parse_badge_arg_with_layer() {
386        let p = parse_badge_arg("prod|red|tr@1");
387        assert_eq!(p.text, "prod");
388        assert_eq!(p.color, Color::Red);
389        assert_eq!(p.anchor, Some(BadgeAnchor::TopRight));
390        assert_eq!(p.layer, Some(1));
391    }
392
393    #[test]
394    fn parse_badge_arg_all_parts() {
395        let p = parse_badge_arg("main|red|tl|20x2");
396        assert_eq!(p.text, "main");
397        assert_eq!(p.color, Color::Red);
398        assert_eq!(p.anchor, Some(BadgeAnchor::TopLeft));
399        assert_eq!(p.width, Some(DimMode::Fixed(20)));
400        assert_eq!(p.lines, Some(DimMode::Fixed(2)));
401    }
402
403    #[test]
404    fn parse_badge_arg_text_with_colon() {
405        let p = parse_badge_arg("time:10:30|blue");
406        assert_eq!(p.text, "time:10:30");
407        assert_eq!(p.color, Color::Blue);
408    }
409
410    #[test]
411    fn parse_badge_arg_auto_dim() {
412        let p = parse_badge_arg("main|red||20a");
413        assert_eq!(p.text, "main");
414        assert_eq!(p.color, Color::Red);
415        assert!(p.anchor.is_none());
416        assert_eq!(p.width, Some(DimMode::Max(20)));
417        assert!(p.lines.is_none());
418    }
419
420    // ── truncate_with_ellipsis ──
421
422    #[test]
423    fn truncate_fits_no_change() {
424        assert_eq!(truncate_with_ellipsis("hello", 10), "hello");
425    }
426
427    #[test]
428    fn truncate_adds_ellipsis() {
429        assert_eq!(truncate_with_ellipsis("hello world", 6), "hello…");
430    }
431
432    // ── wrap_text ──
433
434    #[test]
435    fn wrap_text_single_line() {
436        assert_eq!(wrap_text("hello", 10, 1), "hello");
437    }
438
439    #[test]
440    fn wrap_text_multi_chunks() {
441        let result = wrap_text("hello world", 5, 3);
442        assert_eq!(result, "hello\n worl\nd");
443    }
444
445    #[test]
446    fn wrap_text_last_line_ellipsis() {
447        let result = wrap_text("hello world foo", 5, 2);
448        assert_eq!(result, "hello\n wor…");
449    }
450
451    // ── prepare_badge ──
452
453    fn badge_parts(text: &str, color: Color, width: Option<DimMode>) -> BadgeParts {
454        BadgeParts { text: text.to_string(), color, anchor: None, layer: None, width, lines: None }
455    }
456
457    #[test]
458    fn prepare_badge_auto_width() {
459        let spec = prepare_badge(badge_parts("prod", Color::Red, None), BadgeAnchor::TopLeft, 1, None);
460        assert_eq!(spec.display, "prod");
461        assert_eq!(spec.badge_w, 6);
462        assert_eq!(spec.layer, 0);
463    }
464
465    #[test]
466    fn prepare_badge_fixed_width_truncates() {
467        let spec = prepare_badge(badge_parts("hello world", Color::Red, Some(DimMode::Fixed(10))), BadgeAnchor::TopLeft, 1, None);
468        assert_eq!(spec.display, "hello w…");
469        assert_eq!(spec.badge_w, 10);
470    }
471
472    #[test]
473    fn prepare_badge_auto_up_to() {
474        let spec = prepare_badge(badge_parts("prod", Color::Red, Some(DimMode::Max(20))), BadgeAnchor::TopLeft, 1, None);
475        assert_eq!(spec.badge_w, 6);
476    }
477
478    #[test]
479    fn prepare_badge_respects_layer() {
480        let parts = BadgeParts {
481            text: "main".to_string(),
482            color: Color::Red,
483            anchor: Some(BadgeAnchor::TopRight),
484            layer: Some(2),
485            width: None,
486            lines: None,
487        };
488        let spec = prepare_badge(parts, BadgeAnchor::TopLeft, 1, None);
489        assert_eq!(spec.anchor, BadgeAnchor::TopRight);
490        assert_eq!(spec.layer, 2);
491    }
492
493    #[test]
494    fn prepare_badge_inherits_global_anchor() {
495        let parts = BadgeParts {
496            text: "main".to_string(),
497            color: Color::Red,
498            anchor: None,
499            layer: None,
500            width: None,
501            lines: None,
502        };
503        let spec = prepare_badge(parts, BadgeAnchor::BottomRight, 1, None);
504        assert_eq!(spec.anchor, BadgeAnchor::BottomRight);
505        assert_eq!(spec.layer, 0);
506    }
507
508    // ── BadgeArgs ──
509
510    #[test]
511    fn badge_args_prepare_specs_empty() {
512        let args = BadgeArgs {
513            badges: vec![],
514            badge_width: 0,
515            badge_lines: 1,
516            badge_anchor: "tl".to_string(),
517        };
518        let specs = args.prepare_specs();
519        assert!(specs.is_empty());
520    }
521
522    #[test]
523    fn badge_args_prepare_specs_uses_globals() {
524        let args = BadgeArgs {
525            badges: vec!["main".to_string()],
526            badge_width: 0,
527            badge_lines: 1,
528            badge_anchor: "tr".to_string(),
529        };
530        let specs = args.prepare_specs();
531        assert_eq!(specs.len(), 1);
532        assert_eq!(specs[0].anchor, BadgeAnchor::TopRight);
533        assert_eq!(specs[0].layer, 0);
534        assert_eq!(specs[0].badge_w, 6);
535    }
536}