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 && a.is_finite()
143 && b.is_finite()
144 && b > a
145 {
146 return (a, b);
147 }
148 let mut lo = f64::INFINITY;
149 let mut hi = f64::NEG_INFINITY;
150 for t in self
151 .tasks
152 .iter()
153 .filter(|t| t.start.is_finite() && t.end.is_finite())
154 {
155 lo = lo.min(t.start.min(t.end));
156 hi = hi.max(t.start.max(t.end));
157 }
158 if !lo.is_finite() {
159 (0.0, 1.0)
160 } else if hi <= lo {
161 (lo, lo + 1.0)
162 } else {
163 (lo, hi)
164 }
165 }
166}
167
168fn put_str(buf: &mut Buffer, x: u16, y: u16, max_x: u16, s: &str, style: Style) {
169 for (i, ch) in s.chars().enumerate() {
170 let cx = x as u32 + i as u32;
171 if cx >= max_x as u32 {
172 break;
173 }
174 buf[(cx as u16, y)].set_char(ch).set_style(style);
175 }
176}
177
178impl Gantt {
179 fn render_into(&self, area: Rect, buf: &mut Buffer) {
180 let area = area.intersection(buf.area);
181 let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
182 if inner.width < 4 || inner.height < 2 || self.tasks.is_empty() {
183 return;
184 }
185 let gw = self
186 .tasks
187 .iter()
188 .map(|t| t.label.chars().count())
189 .max()
190 .unwrap_or(0) as u16;
191 let gutter = (gw + 1).min(inner.width / 3);
192 let plot = Rect::new(
193 inner.x + gutter,
194 inner.y,
195 inner.width - gutter,
196 inner.height - 1,
197 );
198 if plot.width == 0 || plot.height == 0 {
199 return;
200 }
201 let (lo, hi) = self.time_range();
202 let col = |t: f64| -> u16 {
203 let f = ((t - lo) / (hi - lo)).clamp(0.0, 1.0);
204 plot.x + (f * (plot.width - 1) as f64).round() as u16
205 };
206 let dim = Style::default().fg(self.theme.as_ref().map_or(Color::DarkGray, |t| t.grid));
207 let text = self
208 .theme
209 .as_ref()
210 .map_or(Style::default(), |t| t.label_style());
211
212 let ticks = nice_ticks(lo, hi, (plot.width as usize / 10).max(2));
214 let step = if ticks.len() >= 2 {
215 ticks[1] - ticks[0]
216 } else {
217 1.0
218 };
219 let ay = inner.bottom() - 1;
220 for v in &ticks {
221 let x = col(*v);
222 for y in plot.y..plot.bottom() {
223 buf[(x, y)].set_char('┊').set_style(dim);
224 }
225 put_str(buf, x, ay, inner.right(), &format_tick(*v, step), dim);
226 }
227
228 for (i, t) in self.tasks.iter().enumerate().take(plot.height as usize) {
229 let y = plot.y + i as u16;
230 let l: String = t
231 .label
232 .chars()
233 .take(gutter.saturating_sub(1) as usize)
234 .collect();
235 put_str(buf, inner.x, y, plot.x, &l, text);
236 if !t.start.is_finite() || !t.end.is_finite() {
237 continue;
238 }
239 let color = t.color.unwrap_or_else(|| self.task_color(i));
240 let (a, b) = (col(t.start.min(t.end)), col(t.start.max(t.end)));
241 crate::interact::record_point(Rect::new(a, y, b - a + 1, 1), 0, i, || {
242 let f = crate::util::format_compact;
243 (
244 t.label.clone(),
245 vec![
246 format!("{} → {}", f(t.start), f(t.end)),
247 format!("progress {:.0}%", t.progress.clamp(0.0, 1.0) * 100.0),
248 ],
249 )
250 });
251 let len = (b - a + 1) as f64;
252 let done = (t.progress.clamp(0.0, 1.0) * len).round() as u16;
253 for (k, x) in (a..=b).enumerate() {
254 let (ch, st) = if (k as u16) < done {
255 ('█', Style::default().fg(color))
256 } else {
257 ('░', Style::default().fg(color))
258 };
259 buf[(x, y)].set_char(ch).set_style(st);
260 }
261 }
262
263 if let Some(t) = self.today.filter(|t| t.is_finite() && *t >= lo && *t <= hi) {
264 let x = col(t);
265 let st = Style::default().fg(self.theme.as_ref().map_or(Color::Red, |t| t.bear));
266 for y in plot.y..plot.bottom() {
267 buf[(x, y)].set_char('┃').set_style(st);
268 }
269 put_str(buf, x, ay, inner.right(), "▲", st);
270 }
271 }
272}
273
274widget_impls!(Gantt);
275
276#[cfg(feature = "theme")]
277impl tui_nuances::Themed for Gantt {
278 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
279 self.theme(theme)
280 }
281}
282
283#[cfg(test)]
284mod tests {
285 use super::*;
286 use ratatui::widgets::Widget;
287
288 fn render(g: &Gantt, w: u16, h: u16) -> Buffer {
289 let area = Rect::new(0, 0, w, h);
290 let mut buf = Buffer::empty(area);
291 g.render(area, &mut buf);
292 buf
293 }
294
295 fn count(b: &Buffer, s: &str) -> usize {
296 b.content().iter().filter(|c| c.symbol() == s).count()
297 }
298
299 #[test]
300 fn progress_fill() {
301 let g = Gantt::new([Task::new("a", 0.0, 10.0).progress(0.5)]);
302 let b = render(&g, 30, 4);
303 assert!(count(&b, "█") > 0 && count(&b, "░") > 0);
304 let full = render(
305 &Gantt::new([Task::new("a", 0.0, 10.0).progress(1.0)]),
306 30,
307 4,
308 );
309 assert_eq!(count(&full, "░"), 0);
310 }
311
312 #[test]
313 fn today_marker_and_labels() {
314 let g =
315 Gantt::new([Task::new("design", 0.0, 5.0), Task::new("build", 5.0, 10.0)]).today(5.0);
316 let b = render(&g, 40, 5);
317 assert!(count(&b, "┃") >= 2);
318 let row0: String = (0..40).map(|x| b[(x, 0)].symbol().to_string()).collect();
319 assert!(row0.starts_with("design"));
320 }
321
322 #[cfg(feature = "theme")]
323 #[test]
324 fn theme_colors_and_override() {
325 let t = Theme::gruvbox();
326 let g = Gantt::new([
327 Task::new("a", 0.0, 5.0),
328 Task::new("b", 5.0, 10.0).color(Color::Red),
329 ])
330 .today(5.0)
331 .theme(&t);
332 let b = render(&g, 40, 5);
333 let fg = |c: Color| b.content().iter().any(|x| x.symbol() == "░" && x.fg == c);
334 assert!(fg(t.color(0)));
335 assert!(fg(Color::Red));
336 assert!(!fg(t.color(1)));
337 assert!(
338 b.content()
339 .iter()
340 .any(|x| x.symbol() == "┃" && x.fg == t.bear)
341 );
342 assert_eq!(b[(39, 0)].bg, t.background.unwrap());
343 }
344
345 #[test]
346 fn tiny_and_nan_no_panic() {
347 let g = Gantt::new([
348 Task::new("x", f64::NAN, 1.0),
349 Task::new("y", 3.0, 3.0).progress(f64::NAN),
350 ])
351 .today(3.0)
352 .block(Block::bordered());
353 for w in 0..8 {
354 for h in 0..6 {
355 render(&g, w, h);
356 }
357 }
358 render(&Gantt::new([]), 10, 5);
359 }
360}