1use crate::theme::{self, Theme};
4use crate::util::{format_tick, nice_ticks};
5use ratatui::{
6 buffer::Buffer,
7 layout::Rect,
8 style::{Color, Style},
9 widgets::Block,
10};
11
12#[derive(Debug, Clone, PartialEq)]
14#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
15pub struct Task {
16 pub label: String,
18 pub start: f64,
20 pub end: f64,
22 pub progress: f64,
24 pub color: Option<Color>,
26}
27
28impl Task {
29 pub fn new(label: impl Into<String>, start: f64, end: f64) -> Self {
31 Self {
32 label: label.into(),
33 start,
34 end,
35 progress: 0.0,
36 color: None,
37 }
38 }
39
40 pub fn progress(mut self, p: f64) -> Self {
42 self.progress = if p.is_finite() {
43 p.clamp(0.0, 1.0)
44 } else {
45 0.0
46 };
47 self
48 }
49
50 opt_setter!(
51 color: Color
53 );
54}
55
56#[derive(Debug, Clone)]
70pub struct Gantt {
71 tasks: Vec<Task>,
72 palette: Option<Vec<Color>>,
73 theme: Option<Theme>,
74 base: Option<Style>,
75 today: Option<f64>,
76 range: Option<(f64, f64)>,
77 block: Option<Block<'static>>,
78}
79
80impl Gantt {
81 pub fn new(tasks: impl IntoIterator<Item = Task>) -> Self {
83 Self {
84 tasks: tasks.into_iter().collect(),
85 palette: None,
86 theme: None,
87 base: None,
88 today: None,
89 range: None,
90 block: None,
91 }
92 }
93
94 opt_setter!(
95 today: f64
97 );
98
99 pub fn range(mut self, start: f64, end: f64) -> Self {
101 self.range = Some((start, end));
102 self
103 }
104
105 pub fn palette(mut self, p: Vec<Color>) -> Self {
107 if !p.is_empty() {
108 self.palette = Some(p);
109 }
110 self
111 }
112
113 theme_setter!(
114 theme
118 );
119
120 base_style_setter!(base);
121
122 fn task_color(&self, i: usize) -> Color {
123 if let Some(p) = &self.palette {
124 return p[i % p.len()];
125 }
126 match &self.theme {
127 Some(t) => t.color(i),
128 None => [
129 Color::Cyan,
130 Color::Green,
131 Color::Yellow,
132 Color::Magenta,
133 Color::LightBlue,
134 ][i % 5],
135 }
136 }
137
138 block_setter!(block, 'static);
139
140 fn time_range(&self) -> (f64, f64) {
141 if let Some((a, b)) = self.range {
142 if a.is_finite() && b.is_finite() && b > a {
143 return (a, b);
144 }
145 }
146 let mut lo = f64::INFINITY;
147 let mut hi = f64::NEG_INFINITY;
148 for t in self
149 .tasks
150 .iter()
151 .filter(|t| t.start.is_finite() && t.end.is_finite())
152 {
153 lo = lo.min(t.start.min(t.end));
154 hi = hi.max(t.start.max(t.end));
155 }
156 if !lo.is_finite() {
157 (0.0, 1.0)
158 } else if hi <= lo {
159 (lo, lo + 1.0)
160 } else {
161 (lo, hi)
162 }
163 }
164}
165
166fn put_str(buf: &mut Buffer, x: u16, y: u16, max_x: u16, s: &str, style: Style) {
167 for (i, ch) in s.chars().enumerate() {
168 let cx = x as u32 + i as u32;
169 if cx >= max_x as u32 {
170 break;
171 }
172 buf[(cx as u16, y)].set_char(ch).set_style(style);
173 }
174}
175
176impl Gantt {
177 fn render_into(&self, area: Rect, buf: &mut Buffer) {
178 let area = area.intersection(buf.area);
179 let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
180 if inner.width < 4 || inner.height < 2 || self.tasks.is_empty() {
181 return;
182 }
183 let gw = self
184 .tasks
185 .iter()
186 .map(|t| t.label.chars().count())
187 .max()
188 .unwrap_or(0) as u16;
189 let gutter = (gw + 1).min(inner.width / 3);
190 let plot = Rect::new(
191 inner.x + gutter,
192 inner.y,
193 inner.width - gutter,
194 inner.height - 1,
195 );
196 if plot.width == 0 || plot.height == 0 {
197 return;
198 }
199 let (lo, hi) = self.time_range();
200 let col = |t: f64| -> u16 {
201 let f = ((t - lo) / (hi - lo)).clamp(0.0, 1.0);
202 plot.x + (f * (plot.width - 1) as f64).round() as u16
203 };
204 let dim = Style::default().fg(self.theme.as_ref().map_or(Color::DarkGray, |t| t.grid));
205 let text = self
206 .theme
207 .as_ref()
208 .map_or(Style::default(), |t| t.label_style());
209
210 let ticks = nice_ticks(lo, hi, (plot.width as usize / 10).max(2));
212 let step = if ticks.len() >= 2 {
213 ticks[1] - ticks[0]
214 } else {
215 1.0
216 };
217 let ay = inner.bottom() - 1;
218 for v in &ticks {
219 let x = col(*v);
220 for y in plot.y..plot.bottom() {
221 buf[(x, y)].set_char('┊').set_style(dim);
222 }
223 put_str(buf, x, ay, inner.right(), &format_tick(*v, step), dim);
224 }
225
226 for (i, t) in self.tasks.iter().enumerate().take(plot.height as usize) {
227 let y = plot.y + i as u16;
228 let l: String = t
229 .label
230 .chars()
231 .take(gutter.saturating_sub(1) as usize)
232 .collect();
233 put_str(buf, inner.x, y, plot.x, &l, text);
234 if !t.start.is_finite() || !t.end.is_finite() {
235 continue;
236 }
237 let color = t.color.unwrap_or_else(|| self.task_color(i));
238 let (a, b) = (col(t.start.min(t.end)), col(t.start.max(t.end)));
239 crate::interact::record_point(Rect::new(a, y, b - a + 1, 1), 0, i, || {
240 let f = crate::util::format_compact;
241 (
242 t.label.clone(),
243 vec![
244 format!("{} → {}", f(t.start), f(t.end)),
245 format!("progress {:.0}%", t.progress.clamp(0.0, 1.0) * 100.0),
246 ],
247 )
248 });
249 let len = (b - a + 1) as f64;
250 let done = (t.progress.clamp(0.0, 1.0) * len).round() as u16;
251 for (k, x) in (a..=b).enumerate() {
252 let (ch, st) = if (k as u16) < done {
253 ('█', Style::default().fg(color))
254 } else {
255 ('░', Style::default().fg(color))
256 };
257 buf[(x, y)].set_char(ch).set_style(st);
258 }
259 }
260
261 if let Some(t) = self.today.filter(|t| t.is_finite() && *t >= lo && *t <= hi) {
262 let x = col(t);
263 let st = Style::default().fg(self.theme.as_ref().map_or(Color::Red, |t| t.bear));
264 for y in plot.y..plot.bottom() {
265 buf[(x, y)].set_char('┃').set_style(st);
266 }
267 put_str(buf, x, ay, inner.right(), "▲", st);
268 }
269 }
270}
271
272widget_impls!(Gantt);
273
274#[cfg(feature = "theme")]
275impl tui_nuances::Themed for Gantt {
276 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
277 self.theme(theme)
278 }
279}
280
281#[cfg(test)]
282mod tests {
283 use super::*;
284 use ratatui::widgets::Widget;
285
286 fn render(g: &Gantt, w: u16, h: u16) -> Buffer {
287 let area = Rect::new(0, 0, w, h);
288 let mut buf = Buffer::empty(area);
289 g.render(area, &mut buf);
290 buf
291 }
292
293 fn count(b: &Buffer, s: &str) -> usize {
294 b.content().iter().filter(|c| c.symbol() == s).count()
295 }
296
297 #[test]
298 fn progress_fill() {
299 let g = Gantt::new([Task::new("a", 0.0, 10.0).progress(0.5)]);
300 let b = render(&g, 30, 4);
301 assert!(count(&b, "█") > 0 && count(&b, "░") > 0);
302 let full = render(
303 &Gantt::new([Task::new("a", 0.0, 10.0).progress(1.0)]),
304 30,
305 4,
306 );
307 assert_eq!(count(&full, "░"), 0);
308 }
309
310 #[test]
311 fn today_marker_and_labels() {
312 let g =
313 Gantt::new([Task::new("design", 0.0, 5.0), Task::new("build", 5.0, 10.0)]).today(5.0);
314 let b = render(&g, 40, 5);
315 assert!(count(&b, "┃") >= 2);
316 let row0: String = (0..40).map(|x| b[(x, 0)].symbol().to_string()).collect();
317 assert!(row0.starts_with("design"));
318 }
319
320 #[cfg(feature = "theme")]
321 #[test]
322 fn theme_colors_and_override() {
323 let t = Theme::gruvbox();
324 let g = Gantt::new([
325 Task::new("a", 0.0, 5.0),
326 Task::new("b", 5.0, 10.0).color(Color::Red),
327 ])
328 .today(5.0)
329 .theme(&t);
330 let b = render(&g, 40, 5);
331 let fg = |c: Color| b.content().iter().any(|x| x.symbol() == "░" && x.fg == c);
332 assert!(fg(t.color(0)));
333 assert!(fg(Color::Red));
334 assert!(!fg(t.color(1)));
335 assert!(b
336 .content()
337 .iter()
338 .any(|x| x.symbol() == "┃" && x.fg == t.bear));
339 assert_eq!(b[(39, 0)].bg, t.background.unwrap());
340 }
341
342 #[test]
343 fn tiny_and_nan_no_panic() {
344 let g = Gantt::new([
345 Task::new("x", f64::NAN, 1.0),
346 Task::new("y", 3.0, 3.0).progress(f64::NAN),
347 ])
348 .today(3.0)
349 .block(Block::bordered());
350 for w in 0..8 {
351 for h in 0..6 {
352 render(&g, w, h);
353 }
354 }
355 render(&Gantt::new([]), 10, 5);
356 }
357}