1use crate::text::put_str;
4use crate::theme::{self, Theme};
5use crate::util::{darken, format_compact};
6use ratatui::{
7 buffer::Buffer,
8 layout::Rect,
9 style::{Color, Style},
10 widgets::Block,
11};
12
13#[derive(Debug, Clone, PartialEq)]
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16pub struct BulletItem {
17 pub label: String,
19 pub value: f64,
21 pub target: Option<f64>,
23 pub ranges: Vec<f64>,
25}
26
27impl BulletItem {
28 pub fn new(label: impl Into<String>, value: f64) -> Self {
30 Self {
31 label: label.into(),
32 value,
33 target: None,
34 ranges: vec![],
35 }
36 }
37
38 pub fn target(mut self, t: f64) -> Self {
40 self.target = Some(t);
41 self
42 }
43
44 pub fn ranges(mut self, r: impl IntoIterator<Item = f64>) -> Self {
46 self.ranges = r.into_iter().collect();
47 self
48 }
49}
50
51#[derive(Debug, Clone, Default)]
65pub struct Bullet {
66 items: Vec<BulletItem>,
67 max: Option<f64>,
68 color: Option<Color>,
69 theme: Option<Theme>,
70 base: Option<Style>,
71 block: Option<Block<'static>>,
72}
73
74fn fin(v: f64) -> f64 {
75 if v.is_finite() { v } else { 0.0 }
76}
77
78impl Bullet {
79 pub fn new(items: impl IntoIterator<Item = BulletItem>) -> Self {
81 Self {
82 items: items.into_iter().collect(),
83 ..Self::default()
84 }
85 }
86
87 pub fn max(mut self, m: f64) -> Self {
90 self.max = Some(m);
91 self
92 }
93
94 pub fn color(mut self, c: Color) -> Self {
96 self.color = Some(c);
97 self
98 }
99
100 theme_setter!(
101 theme
103 );
104
105 base_style_setter!(base);
106
107 block_setter!(block, 'static);
108
109 fn scale_max(&self, it: &BulletItem) -> f64 {
110 let m = self.max.map(fin).unwrap_or_else(|| {
111 it.ranges
112 .iter()
113 .copied()
114 .chain([it.value])
115 .chain(it.target)
116 .map(fin)
117 .fold(0.0, f64::max)
118 });
119 if m > 0.0 { m } else { 1.0 }
120 }
121
122 fn render_into(&self, area: Rect, buf: &mut Buffer) {
123 let area = area.intersection(buf.area);
124 let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
125 if inner.width < 8 || inner.height == 0 || self.items.is_empty() {
126 return;
127 }
128 let lw = (self
129 .items
130 .iter()
131 .map(|i| i.label.chars().count())
132 .max()
133 .unwrap_or(0) as u16)
134 .min(inner.width / 3);
135 let vw = (self
136 .items
137 .iter()
138 .map(|i| format_compact(fin(i.value)).chars().count())
139 .max()
140 .unwrap_or(0) as u16
141 + 1)
142 .min(inner.width / 4);
143 let bx = inner.x + lw + 1;
144 let bw = inner.width.saturating_sub(lw + 1 + vw);
145 if bw < 2 {
146 return;
147 }
148 let th = self.theme.as_ref();
149 let text = th.map_or(Style::default(), |t| t.label_style());
150 let bar = self
151 .color
152 .unwrap_or_else(|| th.map_or(Color::Cyan, |t| t.accent));
153 let marker = th.map_or(Color::White, |t| t.foreground);
154 let bands: [Color; 3] = th.map_or(
155 [
156 Color::Rgb(70, 70, 70),
157 Color::Rgb(52, 52, 52),
158 Color::Rgb(36, 36, 36),
159 ],
160 |t| {
161 let f = t.foreground;
162 [darken(f, 0.68), darken(f, 0.8), darken(f, 0.9)]
163 },
164 );
165 let col = |v: f64, max: f64| -> u16 {
166 ((fin(v) / max).clamp(0.0, 1.0) * (bw - 1) as f64).round() as u16
167 };
168 let n = self.items.len();
170 let avail = inner.height as usize;
171 let (rh, gap) = [(3usize, 1usize), (2, 1), (1, 1), (1, 0)]
172 .into_iter()
173 .find(|(h, g)| n * h + n.saturating_sub(1) * g <= avail)
174 .unwrap_or((1, 0));
175 let total = n * rh + n.saturating_sub(1) * gap;
176 let top = inner.y as usize + avail.saturating_sub(total) / 2;
177 let good = Color::Rgb(80, 200, 120);
178 let warn = Color::Rgb(240, 180, 60);
179 for (i, it) in self.items.iter().enumerate() {
180 let y0 = top + i * (rh + gap);
181 if y0 >= inner.bottom() as usize {
182 break;
183 }
184 let rh = rh.min(inner.bottom() as usize - y0) as u16;
185 let y0 = y0 as u16;
186 let ymid = y0 + rh / 2;
187 put_str(buf, inner.x, ymid, bx, &it.label, text);
188 let max = self.scale_max(it);
189 crate::interact::record_point(Rect::new(bx, y0, bw, rh), 0, i, || {
190 let mut lines = vec![format!("value {}", format_compact(fin(it.value)))];
191 if let Some(t) = it.target.filter(|t| fin(*t) > 0.0) {
192 lines.push(format!("target {}", format_compact(fin(t))));
193 lines.push(format!("{:.0}% of target", fin(it.value) / fin(t) * 100.0));
194 }
195 (it.label.clone(), lines)
196 });
197 let nb = it.ranges.len();
199 let mut shade_at = vec![bands[2]; bw as usize];
200 let mut from = 0u16;
201 for (k, r) in it.ranges.iter().enumerate() {
202 let to = col(*r, max) + 1;
203 let shade = bands[(k * 3 / nb.max(1)).min(2)];
204 for x in from..to.min(bw) {
205 shade_at[x as usize] = shade;
206 }
207 from = from.max(to);
208 }
209 for r in 0..rh {
210 for x in 0..bw {
211 buf[(bx + x, y0 + r)]
212 .set_char(' ')
213 .set_bg(shade_at[x as usize]);
214 }
215 }
216 let frac = (fin(it.value) / max).clamp(0.0, 1.0);
218 let bar_y = y0 + if rh == 1 { 0 } else { rh / 2 };
219 if rh == 1 {
220 let end = col(it.value, max) + u16::from(fin(it.value) > 0.0);
221 for x in 0..end.min(bw) {
222 buf[(bx + x, bar_y)].set_char('▄').set_fg(bar);
223 }
224 } else {
225 let eighths = (frac * bw as f64 * 8.0).round() as u32;
226 for x in 0..bw {
227 let rem = eighths.saturating_sub(x as u32 * 8);
228 let cell = &mut buf[(bx + x, bar_y)];
229 if rem >= 8 {
230 cell.set_char('█').set_fg(bar);
231 } else if rem > 0 {
232 cell.set_char(['▏', '▎', '▍', '▌', '▋', '▊', '▉'][rem as usize - 1])
233 .set_fg(bar);
234 }
235 }
236 }
237 if let Some(t) = it.target {
238 let x = col(t, max).min(bw - 1);
239 for r in 0..rh {
240 buf[(bx + x, y0 + r)]
241 .set_char(if rh == 1 { '│' } else { '┃' })
242 .set_fg(marker);
243 }
244 }
245 let mut vstyle = text;
246 let mut note = String::new();
247 if let Some(t) = it.target.filter(|t| fin(*t) > 0.0) {
248 let pct = fin(it.value) / fin(t) * 100.0;
249 vstyle = vstyle.fg(if pct >= 100.0 { good } else { warn });
250 note = format!(" {pct:.0}%");
251 }
252 let vx = bx + bw + 1;
253 put_str(
254 buf,
255 vx,
256 ymid,
257 inner.right(),
258 &format_compact(fin(it.value)),
259 vstyle,
260 );
261 if !note.is_empty() && rh >= 2 && ymid + 1 < y0 + rh {
262 put_str(
263 buf,
264 vx,
265 ymid + 1,
266 inner.right(),
267 note.trim_start(),
268 Style::default().fg(darken(marker, 0.35)),
269 );
270 }
271 }
272 }
273}
274
275widget_impls!(Bullet);
276
277#[cfg(feature = "theme")]
278impl tui_nuances::Themed for Bullet {
279 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
280 self.theme(theme)
281 }
282}
283
284#[cfg(test)]
285mod tests {
286 use super::*;
287 use ratatui::widgets::Widget;
288
289 fn render(b: &Bullet, w: u16, h: u16) -> Buffer {
290 let a = Rect::new(0, 0, w, h);
291 let mut buf = Buffer::empty(a);
292 b.render(a, &mut buf);
293 buf
294 }
295
296 #[test]
297 fn draws_value_target_and_ranges() {
298 let b = Bullet::new([BulletItem::new("Rev", 70.0)
299 .target(85.0)
300 .ranges([50.0, 80.0, 100.0])]);
301 let buf = render(&b, 40, 2);
302 let all: String = buf.content().iter().map(|c| c.symbol()).collect();
303 assert!(all.contains('█') && all.contains('┃') && all.contains("Rev"));
304 let one = render(&b, 40, 1);
305 let all: String = one.content().iter().map(|c| c.symbol()).collect();
306 assert!(all.contains('▄') && all.contains('│'));
307 assert!(buf.content().iter().any(|c| c.bg != Color::Reset));
308 }
309
310 #[test]
311 fn degenerate_inputs_do_not_panic() {
312 let b = Bullet::new([BulletItem::new("x", f64::NAN).target(f64::INFINITY)]);
313 render(&b, 40, 1);
314 render(&b, 3, 1);
315 render(&b, 0, 0);
316 render(&Bullet::new([]), 20, 3);
317 render(
318 &Bullet::new([BulletItem::new("a", -5.0).ranges([f64::NAN])]).max(0.0),
319 20,
320 3,
321 );
322 }
323
324 #[test]
325 fn custom_color_and_max() {
326 let b = Bullet::new([BulletItem::new("a", 50.0)])
327 .max(200.0)
328 .color(Color::Magenta);
329 let buf = render(&b, 40, 2);
330 assert!(buf.content().iter().any(|c| c.fg == Color::Magenta));
331 let full = |m: f64| {
333 render(&Bullet::new([BulletItem::new("a", 50.0)]).max(m), 40, 2)
334 .content()
335 .iter()
336 .filter(|c| c.symbol() == "█")
337 .count()
338 };
339 assert!(full(100.0) > full(400.0));
340 }
341
342 #[test]
343 fn many_items_and_row_heights() {
344 let items = (0..6).map(|i| BulletItem::new(format!("m{i}"), i as f64 * 10.0));
345 let b = Bullet::new(items);
346 for h in [1, 2, 3, 6, 18, 40] {
347 render(&b, 50, h);
348 }
349 }
350}