Skip to main content

ai_usagebar/
tooltip.rs

1//! Pango-bordered tooltip primitives shared by every vendor renderer.
2//!
3//! Extracted from the per-vendor implementations because every tooltip
4//! (Anthropic, OpenAI, Z.AI, OpenRouter) draws the same kind of box: blue
5//! corners + horizontals, dim separators, centered title, left-padded body
6//! lines. The only thing that varies is the line content.
7//!
8//! Mirrors the visual style of `claudebar`'s `${B}╭${border_h}╮${E}` block
9//! (claudebar:843-859).
10
11use chrono::{DateTime, Utc};
12
13use crate::countdown;
14use crate::pacing;
15use crate::pango::{self, escape, severity_color, severity_for, visible_width};
16use crate::theme::Theme;
17use crate::usage::UsageWindow;
18
19/// One row of the bordered tooltip box.
20pub enum Line {
21    /// Centered text. The renderer pads both sides equally.
22    Center(String),
23    /// Body text. Left-justified, right-padded to fill the box.
24    Body(String),
25    /// A horizontal separator drawn with `─` characters.
26    Sep,
27}
28
29/// Optional decorations for a [`push_window`] row. `Default` reproduces the
30/// plain row every vendor drew before pacing reached the tooltip: bar +
31/// percentage, then `⏱  Resets in …`.
32///
33/// `glyph` is inserted into Pango markup as-is, so a caller passing anything
34/// vendor-reported must [`escape`] it first.
35#[derive(Debug, Clone, Copy, Default)]
36pub struct WindowRow {
37    /// Elapsed-time marker drawn inside the bar (`--tooltip-pace-pts`).
38    pub marker_pct: Option<i32>,
39    /// Pace glyph appended after the bold percentage (`↑` / `→` / `↓`).
40    pub glyph: Option<&'static str>,
41}
42
43impl WindowRow {
44    /// The Anthropic tooltip's pace convention in one place (mirrors
45    /// `widget::render::pick_pace_glyph`): the ratio glyph by default, and with
46    /// `point_mode` (`--tooltip-pace-pts`) the point-delta glyph plus the
47    /// elapsed marker inside the bar.
48    ///
49    /// A window with no reported reset degrades to `pacing::Pacing::neutral()`,
50    /// so it still gets a `→` rather than a blank where every sibling row has
51    /// a glyph.
52    pub fn paced(w: &UsageWindow, now: DateTime<Utc>, tolerance: u32, point_mode: bool) -> Self {
53        let p = pacing::calc(
54            w.utilization_pct,
55            w.resets_at,
56            now,
57            w.window_duration,
58            tolerance,
59        );
60        Self {
61            marker_pct: point_mode.then_some(p.elapsed_pct),
62            glyph: Some(if point_mode {
63                p.point_pace.glyph()
64            } else {
65                p.ratio_pace.glyph()
66            }),
67        }
68    }
69}
70
71/// Append the standard three-line block every vendor uses for a usage window:
72/// icon + label, progress bar + bold percentage, then the dim reset countdown.
73///
74/// `elapsed` draws the pace marker inside the bar; pass `None` for a plain bar.
75/// Keep this signature stable for library callers — a row that also wants the
76/// pace glyph goes through [`push_window_with_row`].
77pub fn push_window(
78    lines: &mut Vec<Line>,
79    label: &str,
80    w: &UsageWindow,
81    theme: &Theme,
82    now: DateTime<Utc>,
83    elapsed: Option<i32>,
84) {
85    push_window_with_row(
86        lines,
87        label,
88        w,
89        theme,
90        now,
91        WindowRow {
92            marker_pct: elapsed,
93            ..WindowRow::default()
94        },
95    );
96}
97
98/// [`push_window`], plus the optional decorations a [`WindowRow`] carries.
99pub fn push_window_with_row(
100    lines: &mut Vec<Line>,
101    label: &str,
102    w: &UsageWindow,
103    theme: &Theme,
104    now: DateTime<Utc>,
105    row: WindowRow,
106) {
107    let color = severity_color(severity_for(w.utilization_pct), theme);
108    let bar = pango::progress_bar(w.utilization_pct, color, theme, row.marker_pct);
109    let fg = &theme.fg;
110    let dim = &theme.dim;
111    let glyph = row.glyph.map(|g| format!(" {g}")).unwrap_or_default();
112    lines.push(Line::Body(format!(
113        " <span foreground='{fg}'>{label}</span>"
114    )));
115    lines.push(Line::Body(format!(
116        "   {bar}  <span font_weight='bold' foreground='{color}'>{pct}%{glyph}</span>",
117        pct = w.utilization_pct
118    )));
119    lines.push(Line::Body(format!(
120        " <span foreground='{dim}'>  ⏱  Resets in {cd}</span>",
121        cd = escape(&countdown::format(w.resets_at, now))
122    )));
123}
124
125/// Render the bordered tooltip. Width is computed from the widest body/center
126/// line so different vendors auto-size correctly.
127pub fn render_bordered(lines: &[Line], theme: &Theme) -> String {
128    let blue = &theme.blue;
129    let dim = &theme.dim;
130
131    let mut max_w: usize = 0;
132    for line in lines {
133        let s = match line {
134            Line::Center(s) | Line::Body(s) => s.as_str(),
135            Line::Sep => continue,
136        };
137        let w = visible_width(s);
138        if w > max_w {
139            max_w = w;
140        }
141    }
142    let inner_w = max_w + 1;
143    let border_h: String = "─".repeat(inner_w);
144    let sep_inner: String = "─".repeat(inner_w.saturating_sub(2));
145    let sep_line = format!(" <span foreground='{dim}'>{sep_inner}</span>");
146
147    let mut out = String::with_capacity(256 * lines.len());
148    out.push_str(&format!("<span foreground='{blue}'>╭{border_h}╮</span>\n"));
149    for line in lines {
150        let body = match line {
151            Line::Body(s) => pad_right(s, inner_w),
152            Line::Center(s) => pad_center(s, inner_w),
153            Line::Sep => pad_right(&sep_line, inner_w),
154        };
155        out.push_str(&format!(
156            "<span foreground='{blue}'>│</span>{body}<span foreground='{blue}'>│</span>\n"
157        ));
158    }
159    out.push_str(&format!("<span foreground='{blue}'>╰{border_h}╯</span>"));
160    out
161}
162
163/// Pad `s` on the right with spaces so its visible width reaches `inner_w`.
164pub fn pad_right(s: &str, inner_w: usize) -> String {
165    let v = visible_width(s);
166    let need = inner_w.saturating_sub(v);
167    format!("{s}{}", " ".repeat(need))
168}
169
170/// Pad `s` symmetrically; when the difference is odd, the extra space goes
171/// on the right (claudebar `center_pad` precedent).
172pub fn pad_center(s: &str, inner_w: usize) -> String {
173    let v = visible_width(s);
174    let total = inner_w.saturating_sub(v);
175    let lp = total / 2;
176    let rp = total - lp;
177    format!("{}{s}{}", " ".repeat(lp), " ".repeat(rp))
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183
184    fn theme() -> Theme {
185        Theme::default()
186    }
187
188    #[test]
189    fn renders_top_and_bottom_borders() {
190        let lines = vec![Line::Center("Hi".into())];
191        let out = render_bordered(&lines, &theme());
192        assert!(out.contains("╭"));
193        assert!(out.contains("╮"));
194        assert!(out.contains("╰"));
195        assert!(out.contains("╯"));
196        assert!(out.contains("Hi"));
197    }
198
199    /// Escaped characters are one glyph wide; if the box measured them by
200    /// source length, rows containing one would stop short of the right border.
201    #[test]
202    fn rows_with_escaped_characters_keep_the_border_flush() {
203        let lines = vec![
204            Line::Body(crate::pango::escape("Claude & GPT (weekly)")),
205            Line::Body("Gemini (weekly)".into()),
206        ];
207        let out = render_bordered(&lines, &theme());
208        let right_edges: Vec<usize> = out.lines().map(crate::pango::visible_width).collect();
209        assert!(
210            right_edges.windows(2).all(|w| w[0] == w[1]),
211            "ragged box: {right_edges:?}\n{out}"
212        );
213    }
214
215    #[test]
216    fn body_line_is_right_padded_to_inner_width() {
217        // Box width = visible_width(widest) + 1 = "longest" (7) + 1 = 8.
218        let lines = vec![Line::Center("a".into()), Line::Body("longest".into())];
219        let out = render_bordered(&lines, &theme());
220        // The body line should be padded so the right `│` lands at inner_w + 2.
221        // We don't assert exact character offsets (Pango spans intervene), just
222        // that the resulting markup is well-formed (open/close balanced).
223        let opens = out.matches("<span").count();
224        let closes = out.matches("</span>").count();
225        assert_eq!(opens, closes);
226    }
227
228    #[test]
229    fn pad_right_strips_pango_tags_before_measuring() {
230        let s = "<span foreground='#fff'>abc</span>"; // visible width 3
231        let p = pad_right(s, 6);
232        // 3 padding spaces appended.
233        assert!(p.ends_with("   "));
234    }
235
236    #[test]
237    fn pad_center_distributes_extra_space_right_for_odd_diff() {
238        let p = pad_center("X", 4); // visible 1, total padding 3 → lp=1, rp=2
239        assert_eq!(p, " X  ");
240    }
241
242    #[test]
243    fn separator_line_width_grows_with_content() {
244        let lines = vec![
245            Line::Center("a".into()),
246            Line::Sep,
247            Line::Body("longer body line".into()),
248        ];
249        let out = render_bordered(&lines, &theme());
250        // The separator should reach the inner width of the box (just check
251        // that it contains the unicode dash glyph repeated).
252        assert!(out.contains("─"));
253    }
254
255    fn at(h: u32) -> DateTime<Utc> {
256        use chrono::TimeZone;
257        Utc.with_ymd_and_hms(2026, 8, 25, h, 0, 0).unwrap()
258    }
259
260    /// One five-hour window `resets_in` hours from `at(12)`.
261    fn window(pct: i32, resets_in: i64) -> UsageWindow {
262        UsageWindow {
263            utilization_pct: pct,
264            resets_at: Some(at(12) + chrono::Duration::hours(resets_in)),
265            window_duration: chrono::Duration::hours(5),
266        }
267    }
268
269    fn row_markup(w: &UsageWindow, row: WindowRow) -> String {
270        let mut lines = Vec::new();
271        push_window_with_row(&mut lines, "  L", w, &theme(), at(12), row);
272        render_bordered(&lines, &theme())
273    }
274
275    /// Every vendor that has not opted into pacing still renders the original
276    /// row; `WindowRow::default()` is what keeps that output untouched.
277    #[test]
278    fn a_default_row_stays_the_plain_bar_percent_and_reset() {
279        let out = row_markup(&window(40, 2), WindowRow::default());
280        assert!(out.contains("40%"), "{out}");
281        assert!(out.contains("Resets in 2h 00m"), "{out}");
282        assert!(
283            !out.contains('↑') && !out.contains('→') && !out.contains('↓'),
284            "an unpaced row must not grow a glyph: {out}"
285        );
286        assert!(!out.contains(" · "), "an unpaced row has no detail: {out}");
287    }
288
289    /// Mirrors the Anthropic tooltip: the ratio glyph always, the elapsed
290    /// marker only behind `--tooltip-pace-pts`.
291    #[test]
292    fn paced_rows_keep_the_marker_behind_point_mode() {
293        // 3h left of a 5h window → 40% elapsed, matched by 40% used.
294        let w = window(40, 3);
295        let ratio = WindowRow::paced(&w, at(12), pacing::DEFAULT_TOLERANCE, false);
296        assert_eq!(ratio.glyph, Some("→"));
297        assert_eq!(ratio.marker_pct, None);
298
299        let points = WindowRow::paced(&w, at(12), pacing::DEFAULT_TOLERANCE, true);
300        assert_eq!(points.glyph, Some("→"));
301        assert_eq!(points.marker_pct, Some(40));
302    }
303
304    /// The two modes disagree inside the tolerance band — the split `pacing`
305    /// documents, and the reason the glyph is picked from the mode.
306    #[test]
307    fn the_pace_modes_can_disagree_on_the_glyph() {
308        let w = window(42, 3); // 40% elapsed, 42% used
309        assert_eq!(WindowRow::paced(&w, at(12), 5, false).glyph, Some("→"));
310        assert_eq!(WindowRow::paced(&w, at(12), 5, true).glyph, Some("↑"));
311    }
312
313    /// A window the vendor reports without a reset still gets a glyph, so a
314    /// row never sits blank beside siblings that have one.
315    #[test]
316    fn a_window_without_a_reset_still_gets_the_neutral_glyph() {
317        let w = UsageWindow {
318            utilization_pct: 0,
319            resets_at: None,
320            window_duration: chrono::Duration::hours(5),
321        };
322        let row = WindowRow::paced(&w, at(12), 5, false);
323        assert_eq!(row.glyph, Some("→"));
324        assert_eq!(row.marker_pct, None);
325    }
326
327    #[test]
328    fn the_glyph_reaches_the_rendered_row() {
329        let w = window(40, 3);
330        let out = row_markup(&w, WindowRow::paced(&w, at(12), 5, false));
331        assert!(out.contains("40% →"), "{out}");
332        assert!(out.contains("Resets in 3h 00m"), "{out}");
333        // The reset line carries nothing after the countdown now that no
334        // vendor appends a fragment to it.
335        assert!(!out.contains("Resets in 3h 00m ·"), "{out}");
336    }
337}